如果我fork()然后执行execv(),那么谁拥有控制台? [英] If I fork() and then do an execv(), who owns the console?

查看:195
本文介绍了如果我fork()然后执行execv(),那么谁拥有控制台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Linux应用程序.如果我调用fork()然后运行需要控制台输入的应用程序,会发生什么情况?考虑下面的代码:

I am writing a Linux application. What happens if I call fork() and then run an application that takes console input? Consider the code below:

int process_id = fork();

if (process_id != 0) {
    /* this is the parent process */
    error = execv("../my_other_app", "parameter1", NULL);
    if (error < 0) {
        printf("error!");
    }
} else {
    /* this is the child process. Wait for my_other_app to set up */
    sleep(3);
    /* now continue */
}

printf("########## press ENTER to stop ##########\n");
getchar();

exit(0);

问题是,my_other_app还有一条按Enter停止消息.因此,当我执行getchar()调用时,哪个应用程序正在读取它?我使用execv启动的主应用程序还是my_other_app?

The thing is, my_other_app also has a press ENTER to stop message. So when I do the getchar() call, which application is reading it? The main application or the my_other_app that I launched with execv?

编辑:通过测试显示,my_other_app的优先级高于控制台.每次都会发生这种情况吗?有没有办法确保控制台由主进程拥有?

It appears through testing that my_other_app takes priority over the console. Does this happen every time? Is there a way to make sure the console is instead owned by the main process?

推荐答案

两个进程都将它们的stdin连接到终端(或与原始进程的stdin连接的任何东西).调用execv时,这不会改变.如果两个进程都尝试同时读取stdin,则无法预测哪个进程将获得输入.

Both processes have their stdin connected to the terminal (or whatever the original process's stdin was connected to). This doesn't change when you call execv. If both processes try to read from stdin at the same time, it's unpredictable which one will get the input.

如果要断开子进程与终端的连接,应先调用setsid(),然后再调用execv将其置于自己的会话中并删除其控制终端.

If you want to disconnect the child process from the terminal, you should call setsid() before calling execv to put it in its own session and remove its controlling terminal.

这篇关于如果我fork()然后执行execv(),那么谁拥有控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆