1

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?

linux: kill background task

Community
  • 1
  • 1
Debadatta Meher
  • 83
  • 2
  • 10
  • I doubt that you get to interrupt the posted script, since it runs to completion without waiting, so it seems that this script does not represent your actual scenario. – Armali Jul 29 '16 at 09:48

1 Answers1

1

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

Community
  • 1
  • 1
rich remer
  • 3,407
  • 2
  • 34
  • 47
  • I used the above code to kill the background processes. It kills the background function/code without waiting for an interrupt. For example, I have a loop in a function that iterates for 10 values of a variable in parent script, which I call later in the parent script and put in background. It will soon get interrupted and killed without even looping to the second iteration. – Debadatta Meher Jul 19 '16 at 16:26
  • You must tell the parent process to wait for its children to exit. This is typically accomplished using the bash builtin `wait` (try `help wait` from the command line). – rich remer Jul 19 '16 at 21:50