...
In this noncompliant code example, if the given user input is '0', the division operation results in a SIGFPE
signal being sent to the program.
Code Block | ||
---|---|---|
| ||
#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   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 when supplied with 0 as an argument.
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
Code Block | ||
---|---|---|
| ||
#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; } |
The only portably safe way to leave a SIGFPE
, SIGILL
, or SIGSEGV
handler is through abort()
or /_Exit()
.
...