3

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.

3
  • ID=command& doesn't do what you think. Commented Dec 1, 2010 at 22:20
  • Sorry, got lazy with the abridging of my code. Edited. Commented Dec 1, 2010 at 22:21
  • why not use kill -9 $PID Commented Nov 10, 2011 at 2:28

7 Answers 7

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

Your $ID matches a command string, while what you need is a PID. Maybe try this:

 ID=`pidof -s command`
 kill -9 $ID

Comments

0

If you command outputs to the terminal, bash will stop it with SIGSTOP, which will make it ignore SIGINT you are sending.

Comments

0

This probably isn't your problem, but the -n is an option for bash's built-in kill command. I would suggest using -NAME instead so that it works for the actual command too.

Comments

0

Some shells that support job control in interactive mode do not enable job control in scripts by default. set -m will enable job control.

Comments

0

Add a wait command right after your kill.

Comments

0

It seems that in case the command is run from a script, it will handle/ignore some signals. Nevertheless, you can still kill the process with SIGKILL (1) like this:

kill -n 1 $ID

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.