How to start two processes as if they were in bash?

I have two commands foo and bar.

foo has been working for a long time without stdin or stdout / stderr activity. bar is a client of foo and works with stdout / stderr, but without stdin activity.

I would like to run them from the same shell, being able to kill both with ctrl-c, and see the output from the line as it happens.

i.e. something like this sequence

foo & bar kill -9

but without the need to manually execute kill - instead, it only happens on ctrl-c

Is there any way to script this?

thanks

+4
source share
2 answers

Do not use kill -9 .

You want to enable the trap on EXIT , not INT .

 trap 'kill $fooPid $barPid' EXIT foo & fooPid=$! bar & barPid=$! wait 

This solution will always terminate foo and bar , regardless of the reason for its exit (excluding its SIGKILL 'ed).

If you want to avoid holding the PID (which has some problems with race conditions), you can do this instead:

 trap 'kill $(jobs -p)' EXIT foo & bar & wait 

This is the best (and cleaner!) Solution if your script has no other tasks.

Ps : These solutions mean foo and bar can write to your terminal (your script stdout ), but none of them can read from stdin . If you need to read either foo or bar with stdin, the solution becomes a bit more complicated.

+5
source

You can configure a bash script to run programs and use trap to capture CTRL-C. Then, in a function called trap, just kill the programs.

It has been some time since I did this, but I think this illustrates the following.

 #!/bin/bash xx() { kill -9 $pid1 kill -9 $pid2 echo bye } trap 'xx' SIGINT sleep 1000 & pid1=$! sleep 2000 & pid2=$! sleep 3600 

Just run this script and CTRL-C, you will find that it kills two sleep processes.

+2
source

All Articles