我正在编写一个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(),那么谁拥有控制台?
发布评论