This question already has an answer here:
-
What's the best way to send a signal to all members of a process group?
32 answers
I wrote a simple bash script which does nothing but sleeps.
#!/bin/bash
echo "Sleeping..."
sleep 180s
I see two processes running on my system after I run the script:
user 22880 0.0 0.0 12428 1412 pts/28 S+ 20:12 0:00 /bin/bash ./sleep.sh
user 22881 0.0 0.0 7196 356 pts/28 S+ 20:12 0:00 sleep 180s
I give a SIGTERM
to the process with id 22880
by using kill -15 22880
which kills the process. However, after this, I still see the sleep command running which exits after 180 seconds.
user 22881 0.0 0.0 7196 356 pts/28 S 20:12 0:00 sleep 180s
Why does this happen? What do I need to do to not leave the sleep 180s
process running?
kill -15 22880
will send a signal to the shell executing the script, but not the sleep
command. To send the signal to every process in the process group, you should be able to specify a negative process ID.
kill -15 -22880
Alternately, ensure that the script kills its children before exiting.
trap 'kill $(jobs -p)' EXIT
echo "Sleeping..."
sleep 180s & wait
If you leave sleep
in the foreground when the signal is received, the shell must wait until it exits before running the trap; sleep
is uninterruptible. The workaround is to run it in the background, then wait
on it. wait
, being a shell built-in, can be interrupted, so that the trap runs immediately and kills any background processes still in progress.
you can also use killall sleep or kill -9/15 $(pidof sleep)
9 use to kill the process and 15 use to terminate the process
bash$ ps -ef|grep sleep
pratik 24775 2695 0 23:44 pts/0 00:00:00 sleep 600
pratik 24778 24690 0 23:44 pts/29 00:00:00 grep --color=auto sleep
bash$ killall sleep
bash$ ps -ef|grep sleep
pratik 24792 24690 0 23:44 pts/29 00:00:00 grep --color=auto sleep
bash$
bash$ ps -ef|grep sleep
pratik 24978 2695 0 23:52 pts/0 00:00:00 sleep 600
pratik 24981 24690 0 23:52 pts/29 00:00:00 grep --color=auto sleep
bash$ kill -15 $(pidof sleep)
bash$ ps -ef|grep sleep
pratik 24986 24690 0 23:52 pts/29 00:00:00 grep --color=auto sleep`