0

Okay, I have a script like this:

trap 'echo "CTRL-C signal was caught!" ' SIGINT
for ((i=0; i<15; i++))
 do
   sleep 3
 done

When I start my script in a usual way, it immediately reacts to CTRL-C command and echo "CTRL-C signal was caught!", even if there is a sleep 3 command. But when I run my script as a background process, it waits until sleep 3 command is finished, and then echo "CTRL-C signal was caught!" I do not understand this. I think trap should wait until previous command is finished, and then it should echo something, like when it started as a background process.

Dari V
  • 43
  • 3
  • 1
    This is more a dupe of [Why do shells ignore SIGINT and SIGQUIT in backgrounded processes?](https://stackoverflow.com/q/45106725/5291015), but given the fact, the answer is not accepted, I'm keeping this open to get more answeers – Inian Jul 28 '20 at 10:03
  • This needs details and clarity, and a [mre]. – oguz ismail Jul 28 '20 at 10:59

1 Answers1

4

Bash manual states:

  • Background processes (...) are immune to keyboard-generated signals.
  • If bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed until the command completes.

Consequently:

  • If your script runs in the foreground: when you press "Ctrl-C", a SIGINT is sent to the currently running process (i.e. the sleep command). The exit status of sleep tells Bash that it was interrupted by the SIGINT signal and bash calls your trap.
  • If your script runs in the background, then the backgrounded sleep does not receive the signal and the SIGINT trap is only executed once sleep has ended.
xhienne
  • 5,738
  • 1
  • 15
  • 34