Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 4.9 chmod,fchmod,andfchmodatFunctions 107


Note that nine of the entries in Figure4.11are the nine file access permission bits from
Figure4.6. We’ve added the two set-ID constants (S_ISUID and S_ISGID), the
saved-text constant (S_ISVTX), and the three combined constants (S_IRWXU,S_IRWXG,
andS_IRWXO).
The saved-text bit (S_ISVTX) is not part of POSIX.1. It is defined in the XSI option in the
Single UNIX Specification.We describe its purpose in the next section.

Example


Recall the final state of the filesfooandbarwhen we ran the program in Figure4.9 to
demonstrate theumaskfunction:
$ls -l foo bar
-rw------- 1 sar 0 Dec 7 21:20 bar
-rw-rw-rw- 1 sar 0 Dec 7 21:20 foo
The program shown in Figure4.12 modifies the mode of these two files.

#include "apue.h"
int
main(void)
{
struct stat statbuf;
/* turn on set-group-ID and turn off group-execute */
if (stat("foo", &statbuf) < 0)
err_sys("stat error for foo");
if (chmod("foo", (statbuf.st_mode & ̃S_IXGRP) | S_ISGID) < 0)
err_sys("chmod error for foo");
/* set absolute mode to "rw-r--r--" */
if (chmod("bar", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0)
err_sys("chmod error for bar");
exit(0);
}

Figure 4.12Example ofchmodfunction

After running the program in Figure4.12, we see that the final state of the two files is
$ls -l foo bar
-rw-r--r-- 1 sar 0 Dec 7 21:20 bar
-rw-rwSrw- 1 sar 0 Dec 7 21:20 foo
In this example, we have set the permissions of the filebarto an absolute value,
regardless of the current permission bits. For the filefoo, we set the permissions
relative to their current state. To dothis, we first callstatto obtain the current
permissions and then modify them.We have explicitly turned on the set-group-ID bit
and turned offthe group-execute bit. Note that thelscommand lists the group-execute
permission asSto signify that the set-group-ID bit is set without the group-execute bit
being set.
Free download pdf