signals/sigmask_longjmp.cThis is signals/sigmask_longjmp.c (Listing 21-2, page 432), an example from the book, The Linux Programming Interface. The source code file is copyright 2024, Michael Kerrisk, and is licensed under the GNU General Public License, version 3. This page shows the "distribution" or "book" version of the file (why are there two versions?), or the differences between the two versions. You can switch between the views using the tabs below. In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.
|
#define _GNU_SOURCE /* Get strsignal() declaration from <string.h> */ #include <string.h> #include <setjmp.h> #include <signal.h> #include "signal_functions.h" /* Declaration of printSigMask() */ #include "tlpi_hdr.h" static volatile sig_atomic_t canJump = 0; /* Set to 1 once "env" buffer has been initialized by [sig]setjmp() */ #ifdef USE_SIGSETJMP static sigjmp_buf senv; #else static jmp_buf env; #endif
static void handler(int sig) { /* UNSAFE: This handler uses non-async-signal-safe functions (printf(), strsignal(), printSigMask(); see Section 21.1.2) */ printf("Received signal %d (%s), signal mask is:\n", sig, strsignal(sig)); printSigMask(stdout, NULL); if (!canJump) { printf("'env' buffer not yet set, doing a simple return\n"); return; } #ifdef USE_SIGSETJMP siglongjmp(senv, 1); #else longjmp(env, 1); #endif }
int main(int argc, char *argv[]) { struct sigaction sa; printSigMask(stdout, "Signal mask at startup:\n"); sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = handler; if (sigaction(SIGINT, &sa, NULL) == -1) errExit("sigaction"); #ifdef USE_SIGSETJMP printf("Calling sigsetjmp()\n"); if (sigsetjmp(senv, 1) == 0) #else printf("Calling setjmp()\n"); if (setjmp(env) == 0) #endif canJump = 1; /* Executed after [sig]setjmp() */ else /* Executed after [sig]longjmp() */ printSigMask(stdout, "After jump from handler, signal mask is:\n" ); for (;;) /* Wait for signals until killed */ pause(); }
Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.