I'm trying to understand what means duplicating a file descriptor after calling fork() and its possible effects on contention.
In "The Linux Programming Interface" 24.2.1 (p517):
When a fork() is performed, the child receives duplicates of all of the parent's file descriptors. These duplicates are made in the manner of dup(), which means that corresponding descriptors in the parent and the child refer to the same open file description.
When I run this same code:
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/wait.h>
int main(void) {
char* fl = "/tmp/test_fd";
int fd;
fd = open(fl, O_CREAT|O_TRUNC|O_WRONLY, 0666);
if(!fork()) {
printf("cfd=%d\n", fd);
_exit(0);
} else {
int status;
printf("ffd=%d\n", fd);
wait(&status);
close(fd);
unlink(fl);
}
}
I get the same file descriptor (number?) for both processes: ffd=3 and cfd=3. But when run this code using dup():
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main(void) {
char* fl = "/tmp/test_fd";
int cfd, ffd;
ffd = open(fl, O_CREAT|O_TRUNC|O_WRONLY, 0666);
cfd = dup(ffd);
printf("ffd=%d\n", ffd);
printf("cfd=%d\n", cfd);
close(ffd);
unlink(fl);
}
I get different file descriptors: ffd=3 and cfd=4.
Then, I have the following questions:
- What means fork() creates a copy of the parent's file descriptors?
- Is there contention when two processes (father and child) perform an operation like fstat() concurrently on the same file descriptor?
- And what about two processes performing fstat() concurrently with two different file descriptors pointing to the same file?