问题
Based on this SO post, and this example, I expect that, when I use fork(), will allow me executing system/execvp in non-blocking manner. However, when I try to issue a long-running child process in a fork block in the above mentioned example code, the control does not return to parent block, till the child has finished.
Can you tell a method, how I should design the code to allow non-blocking calls to system, in C/C++ code. Also, I plan to write a program, where more than one chidren are forked from a same parent. How can I get the pid of the children?
Thanks for your kind help.
回答1:
fork
will immediately return to both the child and parent. However, that example (test3.c) calls wait4, which like it sounds, waits for another process to do something (in this case exit).
回答2:
Mentioned sample code waits for child to return after spawning - that's why it blocks.
To get the pid of child process, use return value of fork(). fork() is single system code which returns two different values - pid of child to parent process and 0 to child process. This is why you can distinguish code blocks in your program which should be executed by parent and children.
Refer to man fork(2).
Another thing you probably should pay attention to concerning fork() and wait() is that after child process exits kernel still holds some information about it (e.g. exit status) which should be consumed somehow. Otherwise such process will become 'zombie' (Z in ps output). This is work done with wait*() calls. Besides, after child exits its parent is notified by kernel with SIGCHLD. If you don't want to process children return values, you can notify system that you're going to ignore SIGCHLD with signal(), sigaction(), etc. In this case that additional data is automatically reaped off. Such behavior may be default on your system but it is still adviseable that you state such behavior explicitly to improve portability of your program.
来源:https://stackoverflow.com/questions/10066591/non-blocking-system-call-in-c-program-using-fork