Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.1a |
both |
#define _POSIX1_SOURCE 2
#include <unistd.h>
int fchown(int fildes, uid_t owner, gid_t group);
Changes the owner or group (or both) of a file. fildes is the file descriptor for the file. owner is the user ID (UID) of the new owner of the file. group is the group ID of the new group for the file.
If _POSIX_CHOWN_RESTRICTED is defined in the unistd.h header file, a process can change the group of a file only if one of the following conditions is true:
Or
If fildes points to a regular file and one or more of the S_IXUSR, S_IXGRP, or S_IXOTH bits of the file mode are set when fchown() returns successfully, it clears the set-user-ID (S_ISUID) and set-group-ID (S_ISGID) bits of the file mode.
If the file referred to by fildes is not a regular file and one or more of the S_IXUSR, S_IXGRP, or S_IXOTH bits of the file mode are set, the set-user-ID (S_ISUID) and set-group-ID (S_ISGID) bits of the file are cleared.
When fchown() completes successfully, it marks the st_ctime field of the file to be updated.
If successful, fchown() updates the change time for the file and returns 0.
⁄* CELEBF04
This example changes the owner ID and group ID.
*⁄
#define _POSIX_SOURCE
#include <fcntl.h>
#include <unistd.h>
#include <sys⁄stat.h>
#include <sys⁄types.h>
#undef _POSIX_SOURCE
#include <stdio.h>
main() {
char fn[]="temp.file";
FILE *stream;
int fd;
struct stat info;
if ((fd = creat(fn, S_IWUSR)) < 0)
perror("creat() error");
else {
stat(fn, &info);
printf("original owner was %d and group was %d\n", info.st_uid,
info.st_gid);
if (fchown(fd, 25, 0) != 0)
perror("fchown() error");
else {
stat(fn, &info);
printf("after fchown(), owner is %d and group is %d\n",
info.st_uid, info.st_gid);
}
close(fd);
unlink(fn);
}
}
original owner was 0 and group was 500
after fchown(), owner is 25 and group is 0