Elegantly get list of descendant processes

processps

I would like to get a list of all the processes that descend (e.g. children, grand-children, etc) from $pid. This is the simplest way I've come up with:

pstree -p $pid | tr "\n" " " |sed "s/[^0-9]/ /g" |sed "s/\s\s*/ /g"

Is there any command, or any simpler way to get the full list of all descendant processes?

Best Answer

The following is somewhat simpler, and has the added advantage of ignoring numbers in the command names:

pstree -p $pid | grep -o '([0-9]\+)' | grep -o '[0-9]\+'

Or with Perl:

pstree -p $pid | perl -ne 'print "$1\n" while /\((\d+)\)/g'

We're looking for numbers within parentheses so that we don't, for example, give 2 as a child process when we run across gif2png(3012). But if the command name contains a parenthesized number, all bets are off. There's only so far text processing can take you.

So I also think that process groups are the way to go. If you'd like to have a process run in its own process group, you can use the 'pgrphack' tool from the Debian package 'daemontools':

pgrphack my_command args

Or you could again turn to Perl:

perl -e 'setpgid or die; exec { $ARGV[0] } @ARGV;' my_command args

The only caveat here is that process groups do not nest, so if some process is creating its own process groups, its subprocesses will no longer be in the group that you created.

Related Question