问题
kill - does it kill the process right away?
I found my answer and I set up a signal handler for SIGCHLD
and introduced wait
in that handler. That way, whenever parent process kill
s a child process, this handler is called and it calls wait
to reap the child. - motive is to clear process table entry.
I am still seeing some child processes going for a few seconds even without its parent process dying. - how is this possible?
I am seeing this via ps
. Precisely ps -o user,pid,ppid,command -ax
and greping for parent process, child process and defunct.
回答1:
A process goes defunct (zombie) immediately upon exiting (from a signal, call to exit
, return from main
, whatever). It stays zombie until wait
'd on by its parent.
So, all processes at least briefly become zombies upon exit.
If the parent process takes a bit (because it was doing other work, or just because the scheduler hasn't given it CPU time yet) before calling wait
, then you'll see the zombie for a bit. If the parent never calls wait
, then when it eventually exits, init
(pid 1) will adopt its zombied children, and call wait
on them.
回答2:
A child process goes defunct (becomes a zombie) only when its parent process hasn't died and hasn't yet waited for it. If the original parent died, then the child's parent becomes process ID 1, and that process's main task is to wait for its (inherited) children to die and remove them from the process list, so that they are not zombies. (Note: an orphaned child, or a daemon, is automatically inherited by PID 1; it does not get assigned to grandparents or great-grandparents up the hierarchy of processes.)
Between the time that the child dies and the parent collects the exit information via wait()
(or waitpid()
, or waitid()
or any of the other variants), it is a zombie in the process list, shown as defunct
by ps
.
But to answer your question's title:
- Yes, a process can go defunct without its parent dying.
(And it can only go defunct if its parent has not died.)
来源:https://stackoverflow.com/questions/8481803/can-a-child-process-go-defunct-without-its-parent-process-dying