fchmod()

Updated: April 19, 2023

Change the permissions for a file

Synopsis:

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

int fchmod( int fd, 
            mode_t mode );

Arguments:

fd
A file descriptor for the file whose permissions you want to change.
mode
The new permissions for the file. For more information, see the entry for struct stat.

Library:

libc

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

Description:

The fchmod() function changes the permissions for a file referred to by fd to be the settings in the mode given by mode.

If the effective user ID of the calling process is equal to the file owner, or the calling process has the IOFUNC_ABILITYID_EXEC ability, fchmod() sets the S_ISUID, S_ISGID and the file permission bits, defined in the <sys/stat.h> header file, from the corresponding bits in the mode argument. These bits define access permissions for the user associated with the file, the group associated with the file, and all others.

For a regular file, if the calling process doesn't have appropriate privileges, and if the group ID of the file doesn't match the effective group ID, the S_ISGID (set-group-ID on execution) bit in the file's mode is cleared upon successful return from fchmod().

Changing the permissions has no any effect on any file descriptors for files that are already open.

If fchmod() succeeds, the st_ctime field of the file is marked for update.

Returns:

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

Errors:

EBADF
Invalid file descriptor.
ENOSYS
The fchmod() function isn't implemented for the filesystem specified by fd.
EPERM
The effective user ID doesn't match the owner of the file, and the calling process doesn't have appropriate privileges.
EROFS
The referenced file resides on a read-only filesystem.

Examples:

/*
 * Change the permissions of a list of files
 * to be read/write by the owner only
 */
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.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( fchmod( fd, S_IRUSR | S_IWUSR ) == -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