Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Killing a process in a script

Tags:

bash

I'm running into a weird behavior for a certain app I'm using. If I start the command in the background in bash, I can kill it using

$ command &
$ kill -n 2 [PID of command]
  killing command gracefully

However, when I throw this into a script:

command &
ID=$!
kill -n 2 $ID

it doesn't do anything at all. Is there some subtly I'm missing?

Edit: Another clue is that once the script stops running, I can't kill the command using kill -n 2.

like image 1000
victor Avatar asked Sep 23 '26 11:09

victor


1 Answers

man 7 signal You are sending a signal 2, INT, to your process, that is Interrupt from keyboard, why ? People are saying to send a signal 1, why ?

The standard gracefully way to kill a process is signal 15, Termination sigal, that is the default used by kill.

So just use kill "$PID"

Then, in case your process run subprocess, you don't just want to kill the father, but you want to kill them all, so use "-$PID" instead of "$PID" to kill the whole process group, but as kill will think that's -"$PID" is a signal number, it will complain, so you'll have to be more precise, as :

kill -15 -"$PID"

If the program don't want to die, use kill -9 -"$PID"

man 7 signal
man kill
like image 74
Julien Palard Avatar answered Sep 25 '26 02:09

Julien Palard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!