File Descriptors are in index into a per-process table.
As we saw in the last section, multiple file descriptors in a process can point to the same file. (newfd = fcntl(fd, F_DUPFD))
This happens across processes as well (a child process inherits the parent's open files )
Information in this table:
This includes flags for the file descriptor (O_CLOEXEC)
A pointer to the open file table.
The file table is system wide
Multiple processes can access the same file at the same time.
This contains per file information
The current file offset.
Flags related to opening the file
The access mode specified in open
Signal related settings
A reference to the inode.
The inode is a file system structure
Contains:
file type
permissions
locks applied to the file.
Timestamps (access, last write, creation ...)
It does NOT contain the file name.
He points out
Two different file descriptors that return to the same file share an offset value.
Reads, writes and seeks in one have an effect on the other.
The DUP family
#include <unistd.h>
int dup(int oldfd);
int dup2(int oldfd, int newfd);
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <fcntl.h> /* Obtain O_* constant definitions */
#include <unistd.h>
int dup3(int oldfd, int newfd, int flags);
Dup will make a copy of the file descriptor at the lowest numbered unused file descriptor.
dup(oldfd);
dup2(oldfd, newfd)
Will make a copy of oldfd at newfd.
If newfd is open, it will close it.
If oldfd is not valid, newfd is not closed, error
If oldfd == newfd, nothing happens.
In both cases, the old and new fd are the same
Except file descriptor flags are not shared (FD_CLOEXEC is off on the new fd)
dup3 is the same as dup2 except
You can set flags on the new fd. (O_CLOEXEC)
An error is returned if oldfd==newfd
This is linux specific.
Return value: valid fd on success or -1 on error.
The man page warns that errors related to closing newfd are lost with dup2 and dup3.