Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop linux bash script when segmentation fault occurs

How to be noticed if calling a program caused segmentation fault in a linux bash script, probably to stop the script then?

like image 595
Ali Avatar asked Nov 19 '12 22:11

Ali


1 Answers

If the program exits with a segmentation fault, or any other error, it will exit with a non-zero exit code. You can test this exit code, and exit your script when it does so. If you want to stop on any error (not just segmentation fault), you can use:

some-crashy-program args || exit 1

If you want to exit your script if any program that you call returns an error (except for as part of an if or while statement), you can just call set -e at the beginning of your script, to cause the script to exit immediately if any command fails. This usage is somewhat discouraged in larger scripts that need to be maintained over time, since it can lead to your script exiting at an unexpected time if something like grep returns a non-zero exit code, but it can be useful for quick one-off scripts if you know that you always want to stop on error.

If you only want to exit if the program crashed with a segfault, not any other error, you can check the specific exit code. On most systems, SEGV has value 11, but you can check with:

$ kill -l SEGV
11

Then add 128 to that, and that will be the exit code your program exits with. Test the exit code against that to find out if your program crashed with SIGSEGV:

some-crashy-program args
if [ $? -eq 139 ]; then
    echo "It crashed!"
    exit 1
fi
like image 100
Brian Campbell Avatar answered Nov 15 '22 07:11

Brian Campbell