non-blocking system call in c++ program using fork

笑着哭i 提交于 2019-12-11 08:25:38

问题


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

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