0

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,

dodgy_command

while SegFault
         dataProcessing
         dodgy_command
end

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

5

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

dodgy_command

while [ $? -ge 128 ]
do
  process_data
  dodgy_command
done

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.

0

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.

#!/bin/bash

# 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
done

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.