fchown() — Change the owner or group by file descriptor

Standards

Standards / Extensions C or C++ Dependencies

POSIX.1a
XPG4.2
Single UNIX Specification, Version 3

both  

Format

#define _POSIX1_SOURCE 2
#include <unistd.h>

int fchown(int fildes, uid_t owner, gid_t group);

General description

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:

  1. The process has appropriate privileges.

    Or

  2. All of the following are true:
    1. The effective user ID of the process is equal to the user ID of the file owner.
    2. The owner argument is equal to the user ID of the file owner or (uid_t)-1,
    3. The group argument is either the effective group ID or a supplementary group ID of the calling process.

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.

Returned value

If successful, fchown() updates the change time for the file and returns 0.

If unsuccessful, fchown() returns -1 and sets errno to one of the following values:
Error Code
Description
EBADF
fildes is not a valid open file descriptor.
EPERM
Either the effective user ID does not match the owner of the file, or the calling process does not have appropriate privileges, and POSIX_CHOWN_RESTRICTED indicates that such privilege is required.
EROFS
The file resides on a read-only system.

Example

CELEBF04
⁄* 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);
  }
}
Output
original owner was 0 and group was 500
after fchown(), owner is 25 and group is 0

Related information