I'm not positive, but I think the shell has not yet updated the value of $?
at the time the handler for CHLD
is called. Consider this script:
set -bm
trap 'echo "Trap result code $?"' CHLD
echo "Script: starting program"
(exit 9)
(exit 11)
echo "Script: result code from program was $?"
I replace your C++ program with a simple subshell that simulates a seg fault. When I run it, the CHLD
trap prints "Trap result code 9", indicating that the trap is seeing the exit status of the command prior to the one that triggers the trap. Changing the value of the first subshell call to exit
changes the value printed by the trap.
The question you link to traps the EXIT
pseudo-signal. Without diving into the bash
source code, I suspect that what happens is this:
Set trap for
CHLD
For each command:
a. Run command
b. Execute trap for signal received
c. Set
$?
Execute
EXIT
trap, if anyExit
In step 2b, the value of $?
corresponding to the command in 2a is not yet available. In step 3, the value of $?
associated with the script is available, because it's the same as the value from 2c, from the last command executed in the script.