Changing File Ownership

When a file is created, the user and group IDs are set to those of the caller. Occasionally it is useful to change ownership of a file or change the group in which the file resides. Only the root user can change the ownership of a file although any user can change the file's group ID to another group in which the user resides.

There are three calls that can be used to change the file's user and group as shown below:

#include <sys/types.h>
#include <unistd.h>

int chown(const char *path, uid_t owner, gid_t group);
int fchown(int fd, uid_t owner, gid_t group);
int lchown(const char *path, uid_t owner, gid_t group);

The difference between chown() and lchown() is that the lchown() system call operates on the symbolic link specified rather than the file to which it points.

Table 2.1 Permissions Passed to chmod()

PERMISSION DESCRIPTION
S_IRWXU Read, write, execute/search by owner
S_IRUSR Read permission by owner
S_IWUSR Write permission by owner
S_IXUSR Execute/search permission by owner
S_IRWXG Read, write, execute/search by group
S_IRGRP Read permission by group
S_IWGRP Write permission by group
S_IXGRP Execute/search permission by group
S_IRWXO Read, write, execute/search by others
S_IROTH Read permission by others
S_IWOTH Write permission by others
S_IXOTH Execute/search permission by others
S_ISUID Set-user-ID on execution
S_ISGID Set-group-ID on execution
S_ISVTX On directories, set the restricted deletion flag

In addition ...

Get UNIX Filesystems: Evolution, Design, and Implementation now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.