Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I want to create a script that runs two programs. That part's simple, but there's a catch: I want to kill the second one if the first one exits. How can I do that?

Edit

I tried killing the program by it's PID after the other one exits, but the program is hamster-time-tracker, which is a Python application that exits immediately, apparently spawning another process. How can I get around this? Is there some way to get the other PID spawned?

Edit 2

Figured it out. I had to run python /usr/bin/hamster-time-tracker instead of hamster-time-tracker, and it stayed running.

share|improve this question

2 Answers 2

up vote 5 down vote accepted
#!/bin/bash

cmd-a &
a=${!}

cmd-b &
b=${!}

wait $a
kill $b

I used yes a and yes b as commands when testing this.

share|improve this answer
1  
+1 for an elegant solution that is easy to understand –  Kenny Rasschaert May 7 '12 at 18:22

There's wait command in the bash to wait for termination of first application and then kill second app.

Since waits are inserted automatically after commands not ending with &, the right order may save you from going into manual wait trouble:

A &
B          # waits
kill $!    # then kills A
share|improve this answer
    
you can find the pid of spawned process using ps aux | grep <name of you process> and then wait for it. –  OJ278 May 7 '12 at 18:05
    
That's not robust in the case of running multiple copies of the same program. –  nickgrim May 7 '12 at 19:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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