Reputation: 103
First of all I would like to say that I've thoroughly searched the solution to my problem in web/stackoverflow..
I'm having the following shell script scenario:
#!/bin/bash
{
while :
do
echo "running"
sleep 2
done
}&
procid=$!
echo $procid
trap "kill -15 $procid" 2 15
Even after interrupting the process with Ctrl-C, the background process is still printing "running" in prompt. I've to kill the background process from terminal using "kill -9 PID", where PID is the process ID of the background process. I tried without the & (not running in background) and the script is terminating well with Ctrl-C.
The solutions to such problem is suggested in these links, however it's not working as desired (The background process is not getting killed). I referred to these links:
How do I kill background processes / jobs when my shell script exits?
Upvotes: 1
Views: 1725
Reputation: 3577
You need to kill the entire process group:
killall () {
PID=$$
kill -9 -$(ps -o pgid= $PID | grep -o '[0-9]*')
}
trap killall EXIT
# ...launch some child processes...
wait
Best way to kill all child processes
Upvotes: 1