signals/t_sigaltstack.cThis is signals/t_sigaltstack.c (Listing 21-3, page 436), 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 <signal.h> #include "tlpi_hdr.h"
static void sigsegvHandler(int sig) { int x; /* UNSAFE: This handler uses non-async-signal-safe functions (printf(), strsignal(), fflush(); see Section 21.1.2) */ printf("Caught signal %d (%s)\n", sig, strsignal(sig)); printf("Top of handler stack near %10p\n", (void *) &x); fflush(NULL); _exit(EXIT_FAILURE); /* Can't return after SIGSEGV */ }
static void /* A recursive function that overflows the stack */ overflowStack(int callNum) { char a[100000]; /* Make this stack frame large */ printf("Call %4d - top of stack near %10p\n", callNum, &a[0]); overflowStack(callNum+1); }
int main(int argc, char *argv[]) { stack_t sigstack; struct sigaction sa; int j; printf("Top of standard stack is near %10p\n", (void *) &j); /* Allocate alternate stack and inform kernel of its existence */ sigstack.ss_sp = malloc(SIGSTKSZ); if (sigstack.ss_sp == NULL) errExit("malloc"); sigstack.ss_size = SIGSTKSZ; sigstack.ss_flags = 0; if (sigaltstack(&sigstack, NULL) == -1) errExit("sigaltstack"); printf("Alternate stack is at %10p-%p\n", sigstack.ss_sp, (char *) sbrk(0) - 1); sa.sa_handler = sigsegvHandler; /* Establish handler for SIGSEGV */ sigemptyset(&sa.sa_mask); sa.sa_flags = SA_ONSTACK; /* Handler uses alternate stack */ if (sigaction(SIGSEGV, &sa, NULL) == -1) errExit("sigaction"); overflowStack(1); }
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.