How does trap / kill work in bash on Linux?

My sample file

traptest.sh:

#!/bin/bash trap 'echo trapped' TERM while : do sleep 1000 done 

$ traptest.sh and

[1] 4280

$ kill% 1 <- kill by job number

Canceled

trapped

$ traptest.sh and

[1] 4280

$ kill 4280 <- kill by process id not working?

(the sound of crickets, the process is not killed)

If I completely remove the trap operator, kill the process id again?

Running some RHEL 2.6.18-194.11.4.el5 at work. I am really confused by this behavior, right?

+8
bash
source share
2 answers
 kill [pid] 

send a TERM signal exclusively to the specified PID.

 kill %1 

send a TERM signal to task number 1 of the entire process group, in this case, to the script pid + his children (sleep).

I checked that with the strace on sleep process and the script process

In any case, someone had a similar problem (but with SIGINT instead of SIGTERM): http://www.vidarholen.net/contents/blog/?p=34 .

Quoting the most important sentence:

kill -INT% 1 sends a signal to the process group, not to the pid!

+4
source share

This is the expected behavior. The default signal sent by kill is SIGTERM , which you capture with your trap. Consider this:

 #!/bin/bash # traptest.sh trap "echo Booh!" SIGINT SIGTERM echo "pid is $$" while : # This is the same as "while true". do a=1 done 

(sleep does create a new process, and the behavior is clearer with my example, I think).

So, if you run traptest.sh in one terminal and kill TRAPTEST_PROCESS_ID from another terminal, the output in the terminal where traptest is Booh! will be Booh! as expected (and the process will NOT be killed) If you try to send kill -s HUP TRAPTEST_PROCESS_ID , it will kill the traptest process.

This should eliminate the confusion of %1 .

Note: sample code is taken from tldp

+6
source share

All Articles