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

1
  • 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. Commented Jul 29, 2016 at 9:48

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.