This is files/t_umask.c (Listing 15-5, page 302), an example from the book, The Linux Programming Interface.

The source code file is copyright 2022, 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
+/* t_umask.c
+   Demonstrate the affect of umask() in conjunction with open() and mkdir().
 #include <sys/stat.h>
 #include <fcntl.h>
 #include "file_perms.h"
 #include "tlpi_hdr.h"
 #define MYFILE "myfile"
 #define MYDIR  "mydir"
 #define DIR_PERMS     (S_IRWXU | S_IRWXG | S_IRWXO)
 main(int argc, char *argv[])
     int fd;
     struct stat sb;
     mode_t u;
     fd = open(MYFILE, O_RDWR | O_CREAT | O_EXCL, FILE_PERMS);
     if (fd == -1)
         errExit("open-%s", MYFILE);
     if (mkdir(MYDIR, DIR_PERMS) == -1)
         errExit("mkdir-%s", MYDIR);
     u = umask(0);               /* Retrieves (and clears) umask value */
     if (stat(MYFILE, &sb) == -1)
         errExit("stat-%s", MYFILE);
     printf("Requested file perms: %s\n", filePermStr(FILE_PERMS, 0));
     printf("Process umask:        %s\n", filePermStr(u, 0));
     printf("Actual file perms:    %s\n\n", filePermStr(sb.st_mode, 0));
     if (stat(MYDIR, &sb) == -1)
         errExit("stat-%s", MYDIR);
     printf("Requested dir. perms: %s\n", filePermStr(DIR_PERMS, 0));
     printf("Process umask:        %s\n", filePermStr(u, 0));
     printf("Actual dir. perms:    %s\n", filePermStr(sb.st_mode, 0));
     if (unlink(MYFILE) == -1)
         errMsg("unlink-%s", MYFILE);
     if (rmdir(MYDIR) == -1)
         errMsg("rmdir-%s", MYDIR);

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