Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

104 Files and Directories Chapter 4


In this example, the set-user-ID program can determine that the real user cannot
normally read the file, even though theopenfunction will succeed.

In the preceding example and in Chapter 8, we’ll sometimes switch to become the superuser to
demonstrate how something works. If you’reonamultiuser system and do not have
superuser permission, you won’t be able to duplicate these examples completely.

4.8 umaskFunction


Now that we’ve described the nine permission bits associated with every file, we can
describe the file mode creation mask that is associated with every process.
Theumaskfunction sets the file mode creation mask for the process and returns the
previous value. (This is one of the few functions that doesn’t have an error return.)
#include <sys/stat.h>
mode_t umask(mode_tcmask);
Returns: previous file mode creation mask

Thecmaskargument is formed as the bitwise OR of any of the nine constants from
Figure4.6:S_IRUSR,S_IWUSR,and so on.
The file mode creation mask is used whenever the process creates a new file or a
new directory.(Recall from Sections 3.3 and 3.4 our description of theopenandcreat
functions. Both accept amodeargument that specifies the new file’s access permission
bits.) Wedescribe how to create a new directory in Section 4.21. Any bits that areonin
the file mode creation mask areturnedoffin the file’smode.

Example


The program in Figure4.9 creates two files: one with aumaskof 0 and one with a
umaskthat disables all the group and other permission bits.
#include "apue.h"
#include <fcntl.h>
#define RWRWRW (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)
int
main(void)
{
umask(0);
if (creat("foo", RWRWRW) < 0)
err_sys("creat error for foo");
umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (creat("bar", RWRWRW) < 0)
err_sys("creat error for bar");
exit(0);
}

Figure 4.9Example ofumaskfunction
Free download pdf