Luisg123v Luisg123v - 2 months ago 13
Linux Question

Why can't I catch process signals when jobs control is enabled in a script?

When I enable jobs control into a shell script (using

set -m
), I am no longer able to catch process signals. Take a look at the following code:

#!/bin/bash

set -m

for i in `seq 15`; do
trap 'echo " Signal $i catched"' $i
done

while true; do
echo " Waiting for a process signal"
sleep 999
done


When I run the above code and I press for example Ctrl + C, nothing happens:

Waiting for a process signal
^CWaiting for a process signal


However, when I run the same code deleting
set -m
, I do get an answer:

Waiting for a process signal
^C Signal 15 catched


My questions are:


  1. Why is it not working?

  2. Is it possible to catch process signals when jobs control is enabled?



Note: It doesn't happen with all processes, if I use
read
instead of
sleep
, it does work.

Answer

The solution is to put sleep in the background and use a bash builtin, wait, to wait while sleep completes. Thus, try this:

#!/bin/bash

set -m

for i in `seq 15`; do
    trap 'echo " Signal $i catched"' $i
done

while true; do
    echo " Waiting for a process signal"
    sleep 999 & wait $!
done

Sample run:

$ bash script
 Waiting for a process signal
^C Signal 15 catched
 Waiting for a process signal
^C Signal 15 catched
 Waiting for a process signal

For more details, see Greg's FAQ.