Your skill will accomplish what the force of many cannot |
|
PerlMonks |
Re: Killing all processes launched using open()by tmoertel (Chaplain) |
on Sep 16, 2004 at 06:38 UTC ( [id://391377]=note: print w/replies, xml ) | Need Help?? |
If you want to "whack" the shell and all of its subprocesses, place
the shell into its own process group. That way, when it forks off
other processes, they will be in the same group, and you can send a
signal to all of them in one fell swoop by killing zero minus the
process group's ID. (You might want to check out the perlipc man
page for more on this stuff.)
Here's some code that shows how to do it. First, we need a troublemaker program to test out our mighty kung-fu on. Here's a shell script that spawns five subprocesses that all emit annoying output. We'll love telling this guy to "kick the oxygen habit" later. And now the Perl code that runs the troublemaker, reads output from it (and its spawn), and after 20 lines kills 'em all off to rescue us from the annoying brood: The run_shell function is where most of the magic happens. It serves as a wrapper around open that gives us more control over the resulting child process. It forks off a child process that has its STDOUT wired to $pipe, which the parent can read from later. The child then starts a new process group with the same ID as its own pid via setpgrp and finally uses exec to run the command we passed in as arguments. Meanwhile, the parent returns from the call to run_shell with a hash containing the pid of and pipe from the child. The parent grabs the pipe's filehandle and reads 20 lines from it, printing each one in passing. Then, getting sick of all the chatter, it sends a hang-up signal to every process in the child's process group, thus shutting their annoying behavior down. Hope this helps. Tom Moertel : Blog / Talks / CPAN / LectroTest / PXSL / Coffee / Movie Rating Decoder
In Section
Seekers of Perl Wisdom
|
|