File Control Operations

The fcntl() system call is designed to provide file control functions for open files. The definition was shown in a previous section, File and Record Locking, earlier in the chapter. It is repeated below:

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

int fcntl(int fildes, int cmd, …);

The file descriptor refers to a previously opened file and the cmd argument is one of the commands shown below:

F_DUPFD. This command returns a new file descriptor that is the lowest numbered file descriptor available (and is not already open). The file descriptor returned will be greater than or equal to the third argument. The new file descriptor refers to the same open file as the original file descriptor and shares any locks. The FD_CLOEXEC (see F_SETFD below) flag associated with the new file descriptor is cleared to keep the file open across calls to one of the exec functions.

F_GETFD. This command returns the flags associated with the specified file descriptor. This is a little bit of a misnomer because there has only ever been one flag, the FD_CLOEXEC flag that indicates that the file should be closed following a successful call to exec().

F_SETFD. This command sets the FD_CLOEXEC flag.

F_GETFL. This command returns the file status flags and file access modes for fildes. The file access modes can be extracted from the return value using the mask O_ACCMODE. The flags are O_RDONLY, O_WRONLY and O_RDWR.

The file status flags, as described in the sections ...

Get UNIX Filesystems: Evolution, Design, and Implementation now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.