$? inside the bash trap

From a bash script, I am trying to handle segmentation errors from a C ++ program. I read that trap on SIGCHLD can be used for this purpose. Inside the trap should I be able to check $? to get the return code from the program. See https://unix.stackexchange.com/questions/24307 .

This does not work for me, and I cannot understand why.

Here is the script:

 #! /bin/bash set -bm trap 'echo "Trap result code $?"' CHLD echo "Script: starting program" ./sigsegv echo "Script: result code from program was $?" 

As you might have guessed, sigsegv simply calls segfault:

 #include <csignal> #include <iostream> using namespace std; int main(int argc, char** argv) { cout << "C++ will now cause a SIGSEGV" << endl; raise(SIGSEGV); cout << "After signal -- shouldn't get here" << endl; return 0; } 

When I run the shell script, I get the following:

 $./wrappersimple.sh Script: starting program C++ will now cause a SIGSEGV Trap result code 0 ./wrapper.sh: line 8: 26368 Segmentation fault (core dumped) ./sigsegv Script: result code from program was 139 

The key was Trap result code 0 . What I expected to say 139 to indicate SIGSEGV (which is 128 base values ​​+ 11 for SIGSEGV).

In case it matters, RHEL 6.2, bash 4.1.2 (1) -release.

+4
source share
1 answer

I'm not sure, but I think the shell has not yet updated the value of $? during a handler call for CHLD . 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 will replace your C ++ program with a simple subshell that mimics a seg error. When I run it, the CHLD trap prints "Result code 9" Trap ", indicating that the trap sees the exit status of the command before the one that starts the trap. Changing the value of the first subshell call to exit changes the value printed by the trap.


The question you associate with exit pseudo-signal traps. Without diving into the bash source, I suspect this is happening:

  • Set a trap for CHLD

  • For each team:

    a. Launch command

    b. Trap for a received signal

    with. Install $?

  • Execute exit trap, if any

  • Exit

In step 2b, the value of $? corresponding to the command in 2a is not yet available. $? value $? available in step 3 $? related to the script, as it matches the value from 2c, from the last command executed in the script.

+4
source

Source: https://habr.com/ru/post/1494143/


All Articles