Due to various reasons the application we have consists of 3 processes which cannot be made into a single one. These processes are quite tightly-knight so it makes sense to spawn and kill them together. For example, if any one of them dies, the whole system won't work so it makes sense to just kill the other two.

Can this be done in Linux?


In general I support G-Man's answer. I'd like to introduce a quick solution that may be enough in some circumstances.

Let the three executables be foo, bar and baz. The assumptions:

  • you can run them by hand;
  • you run all of them as the same user;
  • you run at most one foo, one bar and one baz at any given time.

Instead of foo run foo ; killall bar 2>/dev/null.
Instead of bar run bar ; killall baz 2>/dev/null.
Instead of baz run baz ; killall foo 2>/dev/null.

If you want to run foo in background, the correct syntax is like:

{ foo ; killall bar 2>/dev/null ; } &

Similarly with bar and baz. This way you can run them from a single shell if you wish.

The solution scales to any reasonable number of processes. When one process terminates, a daisy chain of killall will be triggered. This will eventually play thrash metal kill 'em all.

Note you shouldn't start a new set of processes until you know for sure this killing chain is finished.

  • That's clever.  Any particular reason why you use braces in the command instead of parentheses; e.g., (foo ; killall bar 2>/dev/null) &? – G-Man Says 'Reinstate Monica' Jul 26 '17 at 0:23
  • @G-Man No reason. Because of & there's a subshell one way or the other, I think. If there's a difference, it's a subtle one; I haven't investigated it. – Kamil Maciorowski Jul 26 '17 at 7:57

I don’t know of any way to do that directly; i.e., to have Linux handle the process cleanup automatically.  I believe that you will need to have a fourth process that monitors the status of the other three and kills the remaining two when one dies.

If it’s possible to have all three processes started by the same parent process, that’s probably the best approach — have the parent process do a wait(), which will return when any of the child processes terminates.  If that’s not an option, write a new program specifically to do the monitoring.  You’ll have to tell it the PIDs of the three processes.  It can check whether they’re alive by periodically trying to send signal 0 to them.  (The monitoring process will have to run under the same UID as the other processes, or as root (UID 0), in order to have permission to send signals to them.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.