Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 4.8 umaskFunction 105


If we run this program, we can see how the permission bits have been set.
$umask first print the current file mode creation mask
002
$./a.out
$ls -l foo bar
-rw------- 1 sar 0 Dec 7 21:20 bar
-rw-rw-rw- 1 sar 0 Dec 7 21:20 foo
$umask see if the file mode creation mask changed
002

Most users of UNIX systems never deal with theirumaskvalue. It is usually set
once, on login, by the shell’s start-up file, and never changed. Nevertheless, when
writing programs that create new files, if we want to ensurethat specific access
permission bits areenabled, we must modify theumaskvalue while the process is
running. For example, if we want to ensurethat anyone can read a file, we should set
theumaskto 0. Otherwise, theumaskvalue that is in effect when our process is
running can cause permission bits to be turned off.
In the preceding example, we use the shell’sumaskcommand to print the file mode
creation mask both before we run the program and after it completes. This shows us
that changing the file mode creation mask of a process doesn’t affect the mask of its
parent (often a shell). All of the shells have a built-inumaskcommand that we can use
to set or print the current file mode creation mask.
Users can set theumaskvalue to control the default permissions on the files they
create. This value is expressed in octal, with one bit representing one permission to be
masked off, as shown in Figure4.10. Permissions can be denied by setting the
corresponding bits. Some commonumaskvalues are002 to prevent others from
writing your files, 022 to prevent group members and others from writing your files,
and 027 to prevent group members from writing your files and others from reading,
writing, or executing your files.

Mask bit Meaning
0400 user-read
0200 user-write
0100 user-execute
0040 group-read
0020 group-write
0010 group-execute
0004 other-read
0002 other-write
0001 other-execute

Figure 4.10Theumaskfile access permission bits

The Single UNIX Specification requires that the umask command support a
symbolic mode of operation. Unlike the octal format, the symbolic format specifies
which permissions are to be allowed (i.e., clear in the file creation mask) instead of
which ones are to be denied (i.e., set in the file creation mask). Compareboth forms of
the command, shown below.
Free download pdf