I know that after fork()
, all files (and their offsets) opened by the parent are shared
by the child. That is, parent and child share the file table entry of all the files.
What happens if child opens some file. Is it specific to child? Or is it shared by parent?
I've also written small test program. Is this the right way to test this?
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#define FLAG (O_RDWR | O_CREAT | O_TRUNC)
int main(int argc, char *argv[])
{
pid_t pid;
if ((pid = fork()) < 0) {
perror("fork error");
exit(1);
} else if (pid == 0) {
int fc;
if ((fc = open("abc", FLAG)) == -1) {
perror("cannot open abc");
exit(-1);
}
exit(fc);
//returning the file descriptor open through exit()
} else {
int fp;
wait(&fp);
if (fp == -1)
exit(1);
if (fcntl(fp, F_GETFD) == -1)
perror("doesn't work"); //Ouputs: doesn't work: Bad file descriptor
//returns file descriptor flags
//should not return error, if fd is valid
}
return 0;
}
Thanks.