How can I kill all descendents of a process?

How can I kill all descendents of a process?


There isn't a fully general approach to doing this. While you can
determine the relationships between processes by parsing ps
output, this is unreliable in that it represents only a snapshot of the
system.



However, if you're lauching a subprocess that might spawn further
subprocesses of its own, and you want to be able to kill the entire
spawned job at one go, the solution is to put the subprocess into a
new process group, and kill that process group if you need to.



The preferred function for creating process groups is setpgid().
Use this if possible rather than setpgrp() because the latter
differs between systems (on some systems `setpgrp();' is equivalent
to `setpgid(0,0);', on others, setpgrp() and setpgid()
are identical).



See the job-control example in the examples section.



Putting a subprocess into its own process group has a number of effects.
In particular, unless you explicitly place the new process group in the
foreground, it will be treated as a background job with these
consequences:






  • it will be stopped with SIGTTIN if it attempts to read from the
    terminal



  • if tostop is set in the terminal modes, it will be stopped with
    SIGTTOU if it attempts to write to the terminal (attempting to
    change the terminal modes should also cause this, independently of the
    current setting of tostop)



  • The subprocess will not receive keyboard signals from the terminal
    (e.g. SIGINT or SIGQUIT)



In many applications input and output will be redirected anyway, so the
most significant effect will be the lack of keyboard signals. The parent
application should arrange to catch at least SIGINT and
SIGQUIT (and preferably SIGTERM as well) and clean up any
background jobs as necessary.






Home FAQ