fchown()

Change the user ID and group ID of a file

Synopsis:

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

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

Arguments:

fd
A file descriptor for the file whose ownership you want to change.
owner
The user ID of the new owner, or -1 if you don't want to change the owner.
group
The group ID of the new owner, or -1 if you don't want to change the group.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The fchown() function changes the user ID and group ID of the file referenced by fd to be the numeric values contained in owner and group, respectively. It's similar to chown(), but you use a file descriptor instead of a path to identify the file.

Returns:

0
Success.
-1
An error occurred (errno is set).

Errors:

EBADF
Invalid file descriptor.
EPERM
The effective user ID doesn't match the owner of the file, or the calling process doesn't have appropriate privileges.
EROFS
The named file resides on a read-only filesystem.

Examples:

/*
 * Change the ownership of a list of files
 * to the current user/group
 */
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>

int main( int argc, char **argv )
  {
    int i;
    int ecode = 0;
    int fd;

    for( i = 1; i < argc; i++ ) {
      if( ( fd = open( argv[i], O_RDONLY ) ) == -1 ) {
        perror( argv[i] );
        ecode++;
      }
      else if( fchown( fd, getuid(), getgid() ) == -1 ) {
        perror( argv[i] );
        ecode++;
      }

      close( fd );
    }
    return ecode;
  }

Classification:

POSIX 1003.1

Safety:  
Cancellation point No
Interrupt handler No
Signal handler Yes
Thread Yes