From a bash script, I'm trying to handle segmentation faults from a c++ program. I've read that using trap
on SIGCHLD
can be used for this purpose. Inside the trap I should be able to test for $?
to get the return code from the program. See https://unix.stackexchange.com/questions/24307 for example.
It's not working for me, and I can't figure out 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 guess, the sigsegv
program just causes a 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 wrapper script, I get this:
$./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 piece was Trap result code 0
. That's where I expected it to say 139 to indicate a SIGSEGV (which is 128 base value + 11 for SIGSEGV).
In case it matters, RHEL 6.2, bash 4.1.2(1)-release.