Scenario: We have a linux daemon, call it Alpha. Alpha forks/execs a child process, Bravo. Bravo then spawns several child processes, call them Charlie and Delta.
Alpha | \-Bravo | \-Charlie | \-Delta
Bravo dies. Alpha has a sig chil开发者_Go百科d handler installed, which fires.
How do I, from Alpha, locate all the children of Bravo (Charlie and Delta) so that I can kill them as well?
What I have observed is that once Bravo is killed, Charlie and Delta become children of init (pid=1). I either need to be able to 1) examine the process tree BEFORE Bravo's children are reassigned, or 2) ensure somehow that Bravo's children are inherited by Alpha. If that were the case, I could sort out who was who among my (Alpha's) own children.
You can use process groups for this. When Bravo
starts up, have it become a process group leader using setpgid(0, 0);
, before it calls execve()
. Its children will then inherit this process group (which has a PGID equal to the PID of Bravo
, and thus known to Alpha
).
When Bravo
exits, its children will be inherited by init
, but their PGID will not change. Alpha
can then signal them all in one go using kill()
, supplying the negative of the PGID as the first argument. Eg. in Alpha
you might do something like:
exited_child = wait(&status);
if (exited_child > 0)
kill(-exited_child, SIGTERM);
精彩评论