0

I have this:

#!/bin/bash

trap 'echo $? $?' SIGINT

for i in `seq 10`; do
  echo hello from for
  sleep 10
done &

bgproc=$!
echo bgproc is $bgproc
ps -o pid,ppid,cmd
echo "waiting now"
wait $bgproc

I do

kill -2 <pid>

and get

0 0

as o/p

Question:

When I send SIGINT to this script.

Why does it terminate ? I know its because of the wait statement at the end. But whats happening there ?

Idriss Neumann
  • 3,760
  • 2
  • 23
  • 32
Ankur Agarwal
  • 23,692
  • 41
  • 137
  • 208
  • possible duplicate of [Can you access the code of an exit command in a trap?](http://stackoverflow.com/questions/6176834/can-you-access-the-code-of-an-exit-command-in-a-trap) – Ignacio Vazquez-Abrams May 31 '11 at 01:14
  • Not an exact duplicate though. I am also asking how is wait command behaving here. – Ankur Agarwal May 31 '11 at 01:21
  • From bash beginner's guide page 139: "When Bash is waiting for an asynchronous command via the wait built-in, the reception of a signal for which a trap has been set will cause the wait built-in to return immediately with an exit status greater than 128, immediately after which the trap is executed." – Ankur Agarwal May 31 '11 at 01:30
  • Btw: using bash, you don't need to use an external command `seq` to write that kind of `for` loop : `for i in {1..10}`. Here's a [reminder about using command output in loops](https://stackoverflow.com/a/19607361/2900196). – Idriss Neumann Jun 21 '18 at 18:42

1 Answers1

3

From the Bash Reference Manual:

When Bash is waiting for an asynchronous command via the wait builtin, the reception of a signal for which a trap has been set will cause the wait builtin to return immediately with an exit status greater than 128, immediately after which the trap is executed.

Ankur Agarwal
  • 23,692
  • 41
  • 137
  • 208