The Linux Programming Interface

(nextflipdebug5) #1
File Attributes 303

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);
exit(EXIT_SUCCESS);
}
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––– files/t_umask.c

15.4.7 Changing File Permissions: chmod() and fchmod().....................................


The chmod() and fchmod() system calls change the permissions of a file.

The chmod() system call changes the permissions of the file named in pathname. If
this argument is a symbolic link, chmod() changes the permissions of the file to
which it refers, rather than the permissions of the link itself. (A symbolic link is
always created with read, write, and execute permissions enabled for all users, and
these permission can’t be changed. These permissions are ignored when derefer-
encing the link.)
The fchmod() system call changes the permissions on the file referred to by the
open file descriptor fd.
The mode argument specifies the new permissions of the file, either numerically
(octal) or as a mask formed by ORing (|) the permission bits listed in Table 15-4. In
order to change the permissions on a file, either the process must be privileged
(CAP_FOWNER) or its effective user ID must match the owner (user ID) of the file. (To
be strictly accurate, on Linux, for an unprivileged process, it is the process’s file-
system user ID, rather than its effective user ID, that must match the user ID of the
file, as described in Section 9.5.)
To set the permissions on a file so that only read permission is granted to all
users, we could use the following call:

if (chmod("myfile", S_IRUSR | S_IRGRP | S_IROTH) == -1)
errExit("chmod");
/* Or equivalently: chmod("myfile", 0444); */

#include <sys/stat.h>

int chmod(const char *pathname, mode_t mode);

#define _XOPEN_SOURCE 500 /* Or: #define _BSD_SOURCE */
#include <sys/stat.h>

int fchmod(int fd, mode_t mode);
Both return 0 on success, or –1 on error
Free download pdf