2

I did 2 tests about SIGINT using Ctrl+C in bash.

Test 1

Both parent script and child script set a handler by trap.

# !/bin/bash
# Parent.sh
trap 'echo "I handled the SIGINT in Parent.sh and expect the script going ahead."' SIGINT
echo 1.1
./Child.sh
echo 1.2
# !/bin/bash
# Child.sh
trap 'echo "I handled the SIGINT in Child.sh and expect the script going ahead."' SIGINT
echo 2.1
sleep 1000000000
echo 2.2
/tmp:$ ./Parent.sh
1.1
2.1
^CI handled the SIGINT in Child.sh and expect the script going ahead.
2.2
I handled the SIGINT in Parent.sh and expect the script going ahead.
1.2

The output quite tallies with my expectation.

Test 2

Only the child script set a handler by trap.

# !/bin/bash
# Parent.sh
# trap 'echo "I expect I will be terminated immediately after Child.sh died."' SIGINT
echo 1.1
./Child.sh
echo "sleep started"
sleep 5
echo "sleep finished"
echo 1.2
# !/bin/bash
# Child.sh
trap 'echo "I handled the SIGINT in Child.sh and expect the script going ahead."' SIGINT
echo 2.1
sleep 1000000000
echo 2.2
/tmp:$ ./Parent.sh
1.1
2.1
^CI handled the SIGINT in Child.sh and expect the script going ahead.
2.2
sleep started
sleep finished
1.2

I expected the Parent.sh should immediately terminated(as the default action about SIGINT) after Child.sh died.

But it seems Parent.sh received an SIGINT, but it ignored it.

Why it could be this?

Anon
  • 395

1 Answers1

3

That happens because of "Wait and Cooperative Exit" (WCE) which bash implements.

When bash receives a SIGINT signal while waiting for a child, it will only kill itself if the child died because of that signal, not if the child exited. A parent process can determine from the exit status of the child whether it exited or died because of an unhandled signal -- see the WIF* macros in the wait(2) manpage.

A simpler example:

bash -c 'sh -c "trap exit INT; read p"; echo DONE'
<ctrl-C>
DONE

And with the dash shell, which doesn't implement WCE:

dash -c 'sh -c "trap exit INT; read p"; echo DONE'
<ctrl-C>
<no DONE, parent script was killed outright>

See the similar Q&A, and the kludge I've proposed as a work-around.