12

I have a bash script that tests some programs and one of the program returns Segmentation fault so I tried to add a trap in the head of my script:

trap "echo 'segfault occured!'" SIGSEGV

That however didn't do anything. I used

echo $?

just after the program that produces the segfault and I get 139 as output. How can I add a trap for that specific error code?

Pithikos
  • 3,214
  • 4
  • 23
  • 27

2 Answers2

8

trap "$instructions" SIGSEGV traps segmentation faults in the shell itself.

If you run your script under set -e, you can put a trap on EXIT (or 0). It will be executed when your script terminates (whether due to a command returning a nonzero status, or by explicitly calling exit or by falling off the end of the script). To test for a segmentation fault, check $? on entry to the trap. (Note that $? could be 139 because the program returned normally with the status 139; this is avoidable if you do your processing in the shell.)

set -e
trap 'case $? in
        139) echo "segfault occurred";;
      esac' EXIT

In bash or ksh or zsh, you don't need to use set -e to execute a trap after each command that returns a nonzero status, you can put a trap on ERR instead. As before, you need to check $? on entry to the trap, and 139 can (but rarely does) mean that the program returned this status.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
6

From man bash:

   trap [-lp] [[arg] sigspec ...]
          The command arg is to  be  read  and  executed  when  the  shell
          receives  signal(s)  sigspec.

When your program segfaults, your bash just gets a SIGCHLD because some child exited (in whatever way).

You can, however, use the exitcode, stored in $?, in some conditional, and trap SIGCHLD:

trap 'if [[ $? -eq 139 ]]; then echo "segfault !"; fi' CHLD

Note that set -bm might be needed if this (what it probably does) is used in a non-interactive bash (such as a script).

Edit: See also this (Gilles') answer on a similar issue using bash and trap.

sr_
  • 15,224
  • 49
  • 55
  • Something weird happens. I use trap `trap "echo 'something happened!'" {1..64}` and still I don't get anything. I even tryied with `set -bm` and `set -o monitor` but nada. – Pithikos Nov 10 '11 at 16:50
  • Have you tried this interactively? `trap "echo 'something happened'" {1..31}` works for me (leaving out the `!` and those signal specs that lead to `bash: trap: XX: invalid signal specification`). – sr_ Nov 11 '11 at 09:34