Misuse of errno in a signal handler
You read errno after calling an
errno-setting function in a signal handler
Description
This defect occurs when you call one of these functions in a signal handler:
signal: You call thesignalfunction in a signal handler and then read the value oferrno.For instance, the signal handler function
handlercallssignaland then callsperror, which readserrno.typedef void (*pfv)(int); void handler(int signum) { pfv old_handler = signal(signum, SIG_DFL); if (old_handler == SIG_ERR) { perror("SIGINT handler"); } }errno-setting POSIX® function: You call anerrno-setting POSIX function in a signal handler but do not restoreerrnowhen returning from the signal handler.For instance, the signal handler function
handlercallswaitpid, which changeserrno, but does not restoreerrnobefore returning.#include <stddef.h> #include <errno.h> #include <sys/wait.h> void handler(int signum) { int rc = waitpid(-1, NULL, WNOHANG); if (ECHILD != errno) { } }
Risk
In each case that the checker flags, you risk relying on an indeterminate value of
errno.
signal: If the call tosignalin a signal handler fails, the value oferrnois indeterminate (see C11 Standard, Sec. 7.14.1.1). If you rely on a specific value oferrno, you can see unexpected results.errno-setting POSIX function: Anerrno-setting function setserrnoon failure. If you readerrnoafter a signal handler is called and the signal handler itself calls anerrno-setting function, you can see unexpected results.
Fix
Avoid situations where you risk relying on an indeterminate value of
errno.
signal: After calling thesignalfunction in a signal handler, do not readerrnoor use a function that readserrno.errno-setting POSIX function: Before calling anerrno-setting function in a signal handler, saveerrnoto a temporary variable. Restoreerrnofrom this variable before returning from the signal handler.
Examples
Result Information
| Group: Programming |
| Language: C | C++ |
| Default: On for handwritten code, off for generated code |
Command-Line Syntax:
SIG_HANDLER_ERRNO_MISUSE |
| Impact: Medium |
Version History
Introduced in R2018a
See Also
Function called
from signal handler not asynchronous-safe | Errno not checked | Errno not reset | Find defects (-checkers)
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)