|Think about Loose Coupling|
Re: forking, waiting, and killing child pidsby Eliya (Vicar)
|on Apr 11, 2012 at 21:12 UTC||Need Help??|
Your usage of "&" in the command is not only unnecessary (the fork already runs "in the background"), it also is the primary reason your code doesn't work. Otherwise, your approach to create a new process group is perfectly fine, in case you need or want to kill an entire tree of child processes.
Compare the following (I replaced tcpdump with a simple sleep, which is irrelevant to the discussion):
As you can see in the first example, the child process (sleep) dissociates, i.e. the original process (your $snoop PID) is no longer alive, so getpgrp($snoop) fails, and you effectively kill nothing...
In the second example, however, without using "&"1, things work as intended. I.e., you have created a new process group (19538 here), which you are then killing successfully.
That said, unless you actually are running multiple child processes, there is no need to use the process group technique. As long as you can make sure that tcpdump is the only and immediate child process (for example using exec, as noted by halfcountplus (but without your "&" !)), killing that process directly would work without a problem.
BTW, to check whether a process is running, you can send it the "0" pseudo signal, e.g.
1note that I'm using a ";" here in place of the "&", because the example is also meant to show that using an extra process group to kill multiple processes in one go, is working just fine. Without a shell meta character in the command (the semicolon in this case), Perl would optimize away the extra shell, so there would only be a single child process, which kind of defeats the purpose of using a process group...