proc/setjmp_vars.c

This is proc/setjmp_vars.c (Listing 6-6, page 136), 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.

  Cover of The Linux Programming Interface
+/* setjmp_vars.c
+
+   Compiling this program with and without optimization yields different
+   results, since the optimizer reorganizes code and variables in a manner
+   that does not take account of the dynamic flow of control established by
+   a long jump.
+
+   Try looking at the assembler source (.s) for the unoptimized (cc -S)
+   and optimized (cc -O -S) versions of this program to see the cause
+   of these differences.
+*/
 #include <stdio.h>
 #include <stdlib.h>
 #include <setjmp.h>
 
 static jmp_buf env;
 
 static void
 doJump(int nvar, int rvar, int vvar)
 {
     printf("Inside doJump(): nvar=%d rvar=%d vvar=%d\n", nvar, rvar, vvar);
     longjmp(env, 1);
 }
 
 int
 main(int argc, char *argv[])
 {
     int nvar;
     register int rvar;          /* Allocated in register if possible */
     volatile int vvar;          /* See text */
 
     nvar = 111;
     rvar = 222;
     vvar = 333;
 
     if (setjmp(env) == 0) {     /* Code executed after setjmp() */
         nvar = 777;
         rvar = 888;
         vvar = 999;
         doJump(nvar, rvar, vvar);
 
     } else {                    /* Code executed after longjmp() */
 
         printf("After longjmp(): nvar=%d rvar=%d vvar=%d\n", nvar, rvar, vvar);
     }
 
     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.

Valid XHTML 1.1