[Previous]
[Contents]
[Next]

fchmod()

change the permissions for a file

Synopsis:

#include <sys/types.h>
#include <sys/stat.h>
int fchmod( int fd, mode_t mode );

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 appropriate privileges (for example, the super user), 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 does not have appropriate privileges, and if the group ID of the file does not 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 to indicate the error.

Errors:

EBADF
Invalid file descriptor.
EPERM
The effective user ID does not match the owner of the file, and the calling process does not have appropriate privileges.
EROFS
The referenced file resides on a read-only file system.

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:
Interrupt handler No
Signal handler Yes, but modifies errno
Thread Yes

See also:

chmod(), chown(), errno, fchown(), fstat(), open(), stat()


[Previous]
[Contents]
[Next]