signals/nonreentrant.cThis is signals/nonreentrant.c (Listing 21-1, page 424), 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.
|
/* nonreentrant.c Demonstrate the nonreentrant nature of some library functions, in this example, crypt(3). */ #if ! defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < 600 #define _XOPEN_SOURCE 600 #endif #include <unistd.h> #include <signal.h> #include <string.h> #include <crypt.h> #include "tlpi_hdr.h" static char *str2; /* Set from argv[2] */ static volatile int handled = 0; /* Counts number of calls to handler */
static void handler(int sig) { crypt(str2, "xx"); handled++; }
int main(int argc, char *argv[]) { char *cr1; int callNum, mismatch; struct sigaction sa; if (argc != 3) usageErr("%s str1 str2\n", argv[0]); str2 = argv[2]; /* Make argv[2] available to handler */ cr1 = strdup(crypt(argv[1], "xx")); /* Copy statically allocated string to another buffer */ if (cr1 == NULL) errExit("strdup"); sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = handler; if (sigaction(SIGINT, &sa, NULL) == -1) errExit("sigaction"); /* Repeatedly call crypt() using argv[1]. If interrupted by a signal handler, then the static storage returned by crypt() will be overwritten by the results of encrypting argv[2], and strcmp() will detect a mismatch with the value in 'cr1'. */ for (callNum = 1, mismatch = 0; ; callNum++) { if (strcmp(crypt(argv[1], "xx"), cr1) != 0) { mismatch++; printf("Mismatch on call %d (mismatch=%d handled=%d)\n", callNum, mismatch, handled); } } }
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.