Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

If and when the function returns, if the value of sig is SIGFPE, SIGILL, SIGSEGV, or any other implementation-defined value corresponding to a computational exception, the behavior is undefined; otherwise the program will resume execution at the point it was interrupted.

An example of implementation-defined computational exceptions are the SIGTRAP, SIGBUS, and SIGEMT signals in Sun environments.

Noncompliant Code Example

...

Code Block
bgColor#ffcccc
#include<signal.h>
#include<stddef.h>
#include<stdlib.h>

volatile sig_atomic_t denom;

void sighandle(int s){
     /* Fix the offending volatile */
     if (denom == 0) {
           denom = 1;
     }
     /* Everything is ok */
  return;
}

int main(int argc, char *argv[]){
     int result = 0;
    
     if (argc < 2) {
           return 0;
     }
     denom = (int)strtol(argv[1], (char **)NULL, 10);
    
     signal(SIGFPE,(*sighandle));

     result = 100/denom;
     return 0;
}

The noncompliant code example will loop infinitely on most systems input 0 when supplied with 0 as an argument.compiled with gcc 4.3, gcc 3.4, or
This illustrates that even when a SIGFPE handler attempts to fix the error condition while obeying all other rules of signal handling, the behavior may not be as expected.

Compliant Solution

The only portably safe way to leave a SIGFPE, SIGILL, or SIGSEGV handler is through abort() or /_Exit().
In the case of SIGFPE, the default handler calls abort(), so no user defined handler is actually needed. The handler shown is only for consistency.

Code Block
bgColor#ccccff
#include<signal.h>
#include<stddef.h>
#include<stdlib.h>

volatile sig_atomic_t denom;

void sighandle(int s){
     /* No recovery */
     abort();
}

int main(int argc, char *argv[]){
     int result = 0;
    
     if (argc < 2) {
           return 0;
     }
     denom = (int)strtol(argv[1], (char **)NULL, 10);
    
     signal(SIGFPE,(*sighandle));

     result = 100/denom;
     return 0;
}

...

Risk Assessment

Attempting to handle SIGSEGV/SIGILL/or SIGFPE signals is rare. However, code that does rely on handling these signals will usually require a redesign to fix.

...