procexec/footprint.c

This is procexec/footprint.c (Listing 24-3, page 522), 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
+/* footprint.c
+
+   Using fork() + wait() to control the memory footprint of an application.
+
+   This program contains a function that (artificially) consumes a large
+   amount of memory. To avoid changing the process's memory footprint, the
+   program creates a child process that calls the function. When the child
+   terminates, all of its memory is freed, and the memory consumption of
+   the parent is left unaffected.
+*/
 #define _BSD_SOURCE     /* To get sbrk() declaration from <unistd.h> in case
                            _XOPEN_SOURCE >= 600; defining _SVID_SOURCE or
                            _GNU_SOURCE also suffices */
 #include <sys/wait.h>
 #include "tlpi_hdr.h"
 
 static int
 func(int arg)
 {
     int j;
 
     for (j = 0; j < 0x100; j++)
         if (malloc(0x8000) == NULL)
             errExit("malloc");
     printf("Program break in child:  %10p\n", sbrk(0));
 
     return arg;
 }
 
 int
 main(int argc, char *argv[])
 {
     int arg = (argc > 1) ? getInt(argv[1], 0, "arg") : 0;
     pid_t childPid;
     int status;
 
     setbuf(stdout, NULL);           /* Disable buffering of stdout */
 
     printf("Program break in parent: %10p\n", sbrk(0));
 
     childPid = fork();
     if (childPid == -1)
         errExit("fork");
 
     if (childPid == 0)              /* Child calls func() and */
         exit(func(arg));            /* uses return value as exit status */
 
     /* Parent waits for child to terminate. It can determine the
        result of func() by inspecting 'status' */
 
     if (wait(&status) == -1)
         errExit("wait");
 
     printf("Program break in parent: %10p\n", sbrk(0));
 
     printf("Status = %d %d\n", status, WEXITSTATUS(status));
 
     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