This table lists all the functions that POSIX guarantees safe protection against asynchronous signal and therefore can be called from the signal handler.
Using the โwriteโ command from this table, the following relatively ugly solution will hopefully do the trick:
#include <csignal> #ifdef _WINDOWS_ #define _exit _Exit #else #include <unistd.h> #endif #define PRINT_SIGNAL(X) case X: \ write (STDERR_FILENO, #X ")\n" , sizeof(#X ")\n")-1); \ break; void catchSignal (int reason) { char s[] = "Caught signal: ("; write (STDERR_FILENO, s, sizeof(s) - 1); switch (reason) { // These are the handlers that we catch PRINT_SIGNAL(SIGUSR1); PRINT_SIGNAL(SIGHUP); PRINT_SIGNAL(SIGINT); PRINT_SIGNAL(SIGQUIT); PRINT_SIGNAL(SIGABRT); PRINT_SIGNAL(SIGILL); PRINT_SIGNAL(SIGFPE); PRINT_SIGNAL(SIGBUS); PRINT_SIGNAL(SIGSEGV); PRINT_SIGNAL(SIGTERM); } _Exit (1); // 'exit' is not async-signal-safe }
EDIT: Creating windows.
After you try to create this window, it looks like 'STDERR_FILENO' is undefined. From the documentation, however, its meaning looks like "2".
#include <io.h> #define STDIO_FILENO 2
EDIT: "exit" should not be called from a signal handler!
As fizzer pointed out , calling _Exit in the above example is a sledgehammer method for signals such as HUP and TERM. Ideally, when these signals are caught, a flag of type volatile sig_atomic_t can be used to notify the main program that it should exit.
The next thing I found useful in my quest.
source share