CERT-ERR32-C
In this section:
Synopsis
Do not rely on indeterminate values of errno.
Enabled by default
Yes
Severity/Certainty
Low/Low

Full description
A signal handler is allowed to call signal(); if that fails, signal() returns SIG_ERR and sets errno to a positive value. However, if the event that caused a signal was external (not the result of the program calling abort() or raise()), the only functions the signal handler may call are _Exit() or abort(), or it may call signal() on the signal currently being handled; if signal() fails, the value of errno is indeterminate. Using this value results in undefined behavior.
Coding standards
- CERT ERR32-C
Do not rely on indeterminate values of errno
Code examples
The following code example fails the check and will give a warning:
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
typedef void (*pfv)(int);
void handler(int signum) {
pfv old_handler = signal(signum, SIG_DFL);
if (old_handler == SIG_ERR) {
perror("SIGINT handler"); /* Undefined behavior */
/* Handle error */
}
}
int main(void) {
pfv old_handler = signal(SIGINT, handler);
if (old_handler == SIG_ERR) {
perror("SIGINT handler");
/* Handle error */
}
/* Main code loop */
return EXIT_SUCCESS;
}
The following code example passes the check and will not give a warning about this issue:
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
typedef void (*pfv)(int);
void handler(int signum) {
pfv old_handler = signal(signum, SIG_DFL);
if (old_handler == SIG_ERR) {
abort();
}
}
int main(void) {
pfv old_handler = signal(SIGINT, handler);
if (old_handler == SIG_ERR) {
perror("SIGINT handler");
/* Handle error */
}
/* Main code loop */
return EXIT_SUCCESS;
}