I am trying to understand flags and modes of file descriptors.
The man page for
fcntl - manipulate file descriptor
int fcntl(int fd, int cmd);
<
File descriptors can be duplicated. For example, when a process fork
s, it gets its own set of FDs that the parent doesn't affect, and the dup
syscall can be used to explicitly duplicate individual FDs.
When file descriptors get duplicated, every descriptor has its own set of file descriptor flags, but they'll all share the same file status flags. For example, consider this code:
int fdA = open('/tmp/somefile', O_WRONLY);
int fdB = dup(fdA);
fcntl(fdA, F_SETFD, FD_CLOEXEC);
fcntl(fdA, F_SETFL, O_APPEND);
After running it, fdA
will be close-on-exec and in append mode, and fdB
will be in append mode but not close-on-exec. This is because close-on-exec is a file descriptor flag and append mode is a file status flag.
The file access mode and file creation flags are passed along with the file status flags when they're supported.
The third parameter to open
, also confusingly called mode
, is unrelated to everything else discussed so far. If the file is created by the call to open
, then that mode
is used as the permissions for the new file. Otherwise, it has no effect.
FD_CLOEXEC
- file descriptor flagO_RDONLY
- file access modeO_WRONLY
- file access modeO_RDWR
- file access modeO_CLOEXEC
- file creation flagO_CREAT
- file creation flagO_DIRECTORY
- file creation flagO_EXCL
- file creation flagO_NOCTTY
- file creation flagO_NOFOLLOW
- file creation flagO_TMPFILE
- file creation flagO_TRUNC
- file creation flagThe rest of the flags you listed are file status flags.
And one final note: O_CLOEXEC
is only relevant for a new FD. For existing FDs, you'll only ever use FD_CLOEXEC
.