UNIX: Waiting on process children upon exit?

一世执手 提交于 2019-12-11 04:55:32

问题


Let's say I have a C program which spawns some child processes using fork() and exec(). The parent keeps a list of the pids of its children. Once in a while, it tries waiting on them using WNOHANG and informs the user if they have terminated.

The program then decides to exit. Must I explicitly kill and then wait on the remaining child processes so that they don't become zombies? According to Wikipedia:

"Zombie processes should not be confused with orphan processes: an orphan process is a process that is still executing, but whose parent has died. These do not become zombie processes; instead, they are adopted by init (process ID 1), which waits on its children."

So this suggests waiting is unnecessary. But what if the program's children have already become zombies, and the program exits before waiting on them? Basically, will a parent's child processes who are zombies always be reclaimed properly if the parent exits?


回答1:


No, that is the practical definition of a zombie process. Technically a zombie process is any process that has terminated but is still in the process table; however, it's not harmful if the parent process is still around to read the process table and note that the child terminated. A process is more meaningfully a zombie if the parent exits without reading the process table and causing the dead child to be "reaped". However, modern init should quickly wait on any undead children preventing longstanding zombies from roaming the system.

If you consider this carefully, it means all child processes that terminate become zombies for some period of time.

UNIX is morbid.




回答2:


When a process exits, all children become children of process 1 (init). It will promptly reap all zombies. Any children still running will remain running as children of process 1.

Some may argue that it's better to reap your zombies before exiting but it doesn't really matter.



来源:https://stackoverflow.com/questions/23484397/unix-waiting-on-process-children-upon-exit

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