Xiangxin Xiangxin -4 years ago 123
C++ Question

trap fails to catch SIGSEGV

I'm using this script to test trap:


trap "echo segfault!" SIGSEGV
g++ forever.cpp

just runs a recursive function:

void forever(){
int main(){

However it gives
Segmentation fault: 11
instead of printing
. I'm not sure why.

Answer Source

The trap statement traps signals received by bash, not its children. The child receives the segfault and will be exiting with an appropriate exit code. You should therefore check the exit code from the child process. As you can see from here, the exit code is 128+signal number. SEGV is 11 (see man signal), so you will get an exit code of 139. So simply test $? against 139, and you have done.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download