2

I have small script that sets trap and tries to send SIGINT to the child when it receives that signal itself.

However, it doesn't seem to work with sh at all, unlike with bash.

#!/bin/bash

first() {
    trap 'echo "INT first"' INT
    sleep 10
    echo "slept"
}

trap 'echo "killing"; kill -INT "$PID"; echo "kill sent"' INT

first &
PID=$!
echo "$PID"

wait
$ ./test.sh 
64257
^Ckilling
kill sent
INT first
slept

After I change shebang to #!/bin/sh the child doesn't seem to catch the signal.

$ ./test.sh 
64550
^Ckilling
kill sent

String "slept" will be printed after 10 second sleep.

Afkaaja
  • 47
  • 5
  • 1
    I found a way to make the `dash` version of `sh` work the same as `bash`, but I'm not sure about why it works to be comfortable making an answer yet. Two steps: Explicitly turn on job control with `set -m`, and replace `sleep 10` with `sleep 10; wait $!` – Shawn Jul 16 '23 at 06:42
  • As an aside, Control-C sends SIGINT to all the processes in the foreground process group, not just the foreground process. The top-level handler doesn't need to use `kill -INT "$PID"`, as `"$PID"` should already have been sent SIGINT by the OS. – chepner Jul 31 '23 at 22:46

0 Answers0