...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <signal.h> #include <stdio.h> #include <stdlib.h> enum { MAXLINE = 1024 }; volatile sig_atomic_t eflag = 0; char *info = NULL; void log_message(void) { fprintf(stderr, info); } void handler(int signum) { eflag = 1; } int main(void) { if (signal(SIGINT, handler) == SIG_ERR) { /* Handle error */ } info = (char *)malloc(MAXLINE); if (info == NULL) { /* Handle error */ } while (!eflag) { /* Main loop program code */ log_message(); /* More program code */ } log_message(); free(info); info = NULL; return 0; } |
Noncompliant Code Example (longjmp()
)
Invoking the longjmp()
function from within a signal handler can lead to undefined behavior if it results in the invocation of any non-asynchronous-safe functions, likely compromising the integrity of the program. Consequently, neither longjmp()
nor the POSIX siglongjmp()
should ever be called from within a signal handler.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <signal.h> #include <stdlib.h> enum { MAXLINE = 1024 }; volatile sig_atomic_t eflag = 0; void handler(int signum) { eflag = 1; } void log_message(char *info1, char *info2) { static char *buf = NULL; static size_t bufsize; char buf0[MAXLINE]; if (buf == NULL) { buf = buf0; bufsize = sizeof(buf0); } /* * Try to fit a message into buf, else reallocate * it on the heap and then log the message. */ if (buf == buf0) { buf = NULL; } } int main(void) { if (signal(SIGINT, handler) == SIG_ERR) { /* Handle error */ } char *info1; char *info2; /* info1 and info2 are set by user input here */ while (!eflag) { /* Main loop program code */ log_message(info1, info2); /* More program code */ } log_message(info1, info2); return 0; } |
Noncompliant Code Example (raise()
)
In this noncompliant code example, the int_handler()
function is used to carry out tasks specific to SIGINT
and then raises SIGTERM
. However, there is a nested call to the raise()
function, which results in undefined behavior.
...