I want to run three processes which all will stop showing that the service is started and prompt will not be given. I want to automate this procedure. I tried using "&" at the end but it pops in the terminal. I tried using "sh +x script1.sh & sh +x script2.sh" I need to stop the process by pressing ctrl+c for another script to run Please help in this
Asked
Active
Viewed 56 times
1
-
You question is exceedingly terse. You can't abort a program using Ctrl C unless it is running in the foreground. – sjsam Dec 12 '16 at 09:20
-
check this [question](http://stackoverflow.com/questions/356100/how-to-wait-in-bash-for-several-subprocesses-to-finish-and-return-exit-code-0), may be can help you – Joan Esteban Dec 12 '16 at 10:03
-
@sjsam: You can't do it directly, but one could set up a signal handler in the foreground process, which catches the control-c, and then send the corresponding signal to the background process. – user1934428 Dec 12 '16 at 11:09
1 Answers
0
You need to define a general script that launches the three processes in background and waits for the user the press Control+C. Then you add a trap to the general script to launch a shutdown hook.
I think that the solution may look as this:
#!/bin/bash
end_processes() {
echo "Shutdown hook"
if [ -n $PID1 ]; then
echo "Killing PID 1 = $PID1"
kill -9 $PID1
fi
if [ -n $PID2 ]; then
echo "Killing PID 2 = $PID2"
kill -9 $PID2
fi
if [ -n $PID2 ]; then
echo "Killing PID 3 = $PID3"
kill -9 $PID3
fi
}
# Main code: Add trap
trap end_processes EXIT
# Main code: Launch scripts
./script1.sh &
PID1=$!
./script2.sh &
PID2=$!
./script3.sh &
PID3=$!
# Main code: wait for user to press Control+C
while [ 1 ]; do
sleep 1s
done
Notice that:
- I have added some echo messages just to test.
- Trap executes a function when EXIT is received on the script. You can change the received signal by capturing only a specific signal (i.e. SIGINT)
- The trap function is now killing the processes with -9. I you wish, you can send other kill signals
- The $! retrieves the PID of the most recent backgroud command.
You can modify the wait loop (the last while command) to sleep firstly for the aproximate time of the processes to finish and then to wait for a more smaller time:
APROX_TIME=30s POLL_TIME=2s sleep $APROX_TIME while [ 1 ]; do sleep $POLL_TIME done

Cristian Ramon-Cortes
- 1,838
- 1
- 19
- 32
-
@Shreyas please consider [accepting this answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) if it was usefull. – Cristian Ramon-Cortes Aug 09 '17 at 08:54