views:

2684

answers:

2

What's the best way to kill a process and all its child processes from a Perl script? It should run at least under Linux and Solaris, and not require installation of any additional packages.

My guess would be to get a list of all processes and their parents by parsing files in /proc or by parsing the output of ps (neither of which seems portable between Linux and Solaris); and then killing all processes in the tree (which seems prone to race conditions).

I could live with the race conditions in this particular case, but how do I portably get the process list?

+7  A: 

If you can live with killing a process group, you can use the following:

kill -$signum, $pgid;

where $signum is the signal number, and $pgid is the process group ID. However, signal numbers aren't very portable, in which case you can (on some platforms; read perlfunc for explanation) do the following (to send SIGTERM, for example):

kill 'TERM', -$pgid;
Chris Jester-Young
Which processes do belong to a process group? I'm using IPC::Open3 to start a process (which on Solaris runs the command inside sh -c), and I want to kill the sh and my actual command and all further subprocesses. What if the process group contains even the Perl interpreter? Can't that happen?
oliver
As long as you're not using SIGKILL, you can make your Perl program ignore the signal you're sending. Read perlipc (search for "process group").
Chris Jester-Young
+8  A: 

CPAN has an answer. Yes, I know you did not want to install additional modules, but at least you can look at the implementation and see what they are doing...

http://search.cpan.org/~durist/Proc-ProcessTable-0.39/ProcessTable.pm

Arkadiy