UNIX: Waiting on process children upon exit?

2019-08-09 04:36发布

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?

2条回答
贼婆χ
2楼-- · 2019-08-09 05:07

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.

查看更多
劫难
3楼-- · 2019-08-09 05:17

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.

查看更多
登录 后发表回答