timers/timed_read.cThis is timers/timed_read.c (Listing 23-2, page 486), 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.
|
/* timed_read.c Demonstrate the use of a timer to place a timeout on a blocking system call (read(2) in this case). */ #include <signal.h> #include "tlpi_hdr.h" #define BUF_SIZE 200
static void /* SIGALRM handler: interrupts blocked system call */ handler(int sig) { printf("Caught signal\n"); /* UNSAFE (see Section 21.1.2) */ }
int main(int argc, char *argv[]) { struct sigaction sa; char buf[BUF_SIZE]; ssize_t numRead; int savedErrno; if (argc > 1 && strcmp(argv[1], "--help") == 0) usageErr("%s [num-secs [restart-flag]]\n", argv[0]); /* Set up handler for SIGALRM. Allow system calls to be interrupted, unless second command-line argument was supplied. */ sa.sa_flags = (argc > 2) ? SA_RESTART : 0; sigemptyset(&sa.sa_mask); sa.sa_handler = handler; if (sigaction(SIGALRM, &sa, NULL) == -1) errExit("sigaction"); alarm((argc > 1) ? getInt(argv[1], GN_NONNEG, "num-secs") : 10); numRead = read(STDIN_FILENO, buf, BUF_SIZE); savedErrno = errno; /* In case alarm() changes it */ alarm(0); /* Ensure timer is turned off */ errno = savedErrno; /* Determine result of read() */ if (numRead == -1) { if (errno == EINTR) printf("Read timed out\n"); else errMsg("read"); } else { printf("Successful read (%ld bytes): %.*s", (long) numRead, (int) numRead, buf); } exit(EXIT_SUCCESS); }
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.