我正在编写 Linux 应用程序。如果我调用 fork()
然后运行一个接受控制台输入的应用程序会怎样?考虑以下代码:
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
?
编辑:通过测试,my_other_app
似乎优先于控制台。每次都会出现这种情况吗?有没有办法确保控制台由主进程拥有?
最佳答案
两个进程都将它们的 stdin
连接到终端(或者原始进程的 stdin
连接到的任何东西)。当您调用 execv
时,这不会改变。如果两个进程同时尝试从 stdin
中读取,则无法预测哪个进程会获得输入。
如果要断开子进程与终端的连接,应在调用execv
之前调用setsid()
将其置于自己的 session 中并移除其控制终端.
关于c - 如果我 fork() 然后执行 execv(),谁拥有控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21493622/