I have a program that throws a segmentation fault on certain circumstances. I want to execute a command when the segmentation fault occurs to process the data, then execute the command again, and keep doing so until the segmentation fault stops.

As a rough attempt at pseudo code,


while SegFault

I think I need to be using a Trap command, but I don't understand the syntax for this command.


When a program aborts abnormally the exit code (as seen by the shell) typically has the high bit set so the value is 128 or higher. So a simple solution might be


while [ $? -ge 128 ]

If you specifically only want a segfault and not any other type of error, the while line becomes $? -eq 139 (because SEGV is signal 11; 128+11=139).

If you don't get an high valued exit code on failure then it probably means the application is trapping the error, itself, and forcing a different exit code.


You don't mention what language you need to do this in. So, I'm assuming shell script.

You are correct, you want to use a trap. The trap in bash takes a string to execute when a signal is received. I tend to make it a function call so I can clearly define what I want done when I trap the signal.

Here is a sample script.


# define the function that will handle the trap
sigSegFault() { echo "Inside sigSegFault"; }

# Trap the Segmentation Violation (signal 11) signal
trap sigSegFault SEGV

# Start infinite loop    
while [[ true ]]; do
  sleep 10

exit 0

Simplistic, but contains the basics of what you are asking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.