user1131035
user1131035

Reputation: 3

Trapping SIGINT in a backgrounded process

I am trying to understand some sample code describing signal handling in bash. In Example 32-7 at http://tldp.org/LDP/abs/html/debugging.html, the writer's comments state that he is capturing a SIGINT, yet the trap is for EXIT.

{
     trap "exit" SIGUSR1
     sleep $interval; sleep $interval
     while true; do
         ...
     done; } &         # Start a progress bar as a background process.

pid=$!
trap "echo !; kill -USR1 $pid; wait $pid"  EXIT        # To handle ^C.

Why does a trap of EXIT send the correct signal (SIGUSR1) to the backgroud process on a SIGINT (Ctl-C)?

Any help is appreciated explaining why this works.

Upvotes: 0

Views: 737

Answers (2)

Jason Coco
Jason Coco

Reputation: 78393

EXIT is a special handler in trap for bash, it's not a signal. There is no exit signal. This trap gets executed whenever the bash processes terminates. So, what this does is make sure that if the user kills the bash process, SIGUSR1 is sent to the background process, which also is trapped and then executes 'exit' on that process. That makes sure if you kill the session, the background process doesn't live on forever but also quits (which is probably what the comment is trying to explain).

edit: I misread this question in my original response

Upvotes: 1

tripleee
tripleee

Reputation: 189830

The EXIT pseudo-signal is raised both on normal exit and when the script is being interrupted.

Upvotes: 0

Related Questions