tags:

views:

339

answers:

3

I would like to use killall on a process of the same name from which killall will be executed without killing the process spawning the killall.

So in more detail, say I have process foo, and process foo is running. I want to be able to run "foo -k", and have the new foo kill the old foo, without killing itself.

+2  A: 
pgrep foo | grep -v $$ | xargs kill

If you don't have pgrep, you'll have to come up with some other way of generating the list of PIDs of interest. Some options are:

  1. Use ps with appropriate options, followed by some combination of grep, sed and/or awk to match the processes and extract the PIDs.

  2. killall can send a signal 0 instead of SIGTERM; the standard semantics of this is that it doesn't send a signal, but just determines if the process is alive or not. Perhaps you can use killall to select the process list and get it to print the PIDs of the matching ones that are alive. This would also probably require a bit of post-processing with sed.

  3. There may be something along the lines of Linux's /proc filesystem with pseudo-files holding system data that you could grovel through. Again, grep/awk/sed are your friends here.

If you truly need particular details on how to do this, comment or send me mail, and I'll try expanding some of these options in more detail.

[Edits: added further options for those without pgrep.]

Curt Sampson
Nice! I should have stipulated though that it needs to be able to be done in the context of the default OS X install, which doesn't appear to have pgrep.
Does it have pidof?
bdonlan
+1  A: 

This seems to work on OS X:

killall -s foo | perl -ne 'system $_ unless /\b'$PPID'\b/'

killall -s lists what it would do, one PID at a time. Do what it would do except for killing yourself.

Josh Kelley
Note that -s behaves differently on Linux, so be careful if you port this in the future.
bdonlan
+1  A: 

The usual way to solve this is to have foo write its process ID to a file, say something like /var/run/foo.pid when it is run in daemon mode. Then you can have the non-daemon version read the PID from the PID file and call kill(2) on it directly. This is usually how apache and the like handle it. Of course the newer OSX daemons go through launchd(8) instead, but there are still a few that use good old fashioned signals.

D.Shawley