302 Chapter 15
Listing 15-5 illustrates the use of umask() in conjunction with open() and
mkdir(). When we run this program, we see the following:
$ ./t_umask
Requested file perms: rw-rw---- This is what we asked for
Process umask: ----wx-wx This is what we are denied
Actual file perms: rw-r----- So this is what we end up with
Requested dir. perms: rwxrwxrwx
Process umask: ----wx-wx
Actual dir. perms: rwxr--r--
In Listing 15-5, we employ the mkdir() and rmdir() system calls to create and
remove a directory, and the unlink() system call to remove a file. We describe
these system calls in Chapter 18.
Listing 15-5: Using umask()
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––– files/t_umask.c
#include <sys/stat.h>
#include <fcntl.h>
#include "file_perms.h"
#include "tlpi_hdr.h"
#define MYFILE "myfile"
#define MYDIR "mydir"
#define FILE_PERMS (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)
#define DIR_PERMS (S_IRWXU | S_IRWXG | S_IRWXO)
#define UMASK_SETTING (S_IWGRP | S_IXGRP | S_IWOTH | S_IXOTH)
int
main(int argc, char *argv[])
{
int fd;
struct stat sb;
mode_t u;
umask(UMASK_SETTING);
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));