If I fork() and then do an execv(), who owns the console?

爱⌒轻易说出口 提交于 2019-12-04 18:20:30

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.

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() calls dup() on every single file descriptor. In effect you get a copy of all the files in the child. Some "processes" (via hooks) may detect the fork() and close some file descriptors, but that's very unlikely. Some files may be opened with a specific flag saying that it should be closed on execv(). stdin is not one of them.

You have two solutions, just close stdin in the child process, but that can cause problems, or replace it with /dev/null.

freopen("/dev/null", "r", stdin);

You can do the same for stdout and stderr.


Adding a 'wait forever' at the end of the program (since you cannot do getchar() anymore):

for(;;) sleep(0x7FFFFFFF); // for(;;) is probably superfluous

That's probably the simplest way, there are many others such as using select() on a file you know will never change...

I think it APPEARS as though my_other_app has priority since the other child process has sleep(3).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!