As far I understand it, Fds are integers that are used to look up the open files in the kernel's file description table. So therefore if you have a code segment like this:
int fd[2], temp1, temp2;
pipe(fd);
temp1 = fd[0];
temp2 = fd[1];
close(temp1);
close(temp2);
All the file descriptors to the pipe are closed and thus the pipe would no longer exist. Since FDs are simply ints, saying close(temp1)
is identical to saying close(fd[0])
.
In light of all this (and please let me know if I am misunderstanding) I am confused by what happens after a fork()
call. Since the child process inherits the same FDs and state of the parent, the child's FDs should be the same ints as the parents. So by that logic, if I close(fd[0])
in the child, I believe it would also prevent the parent from accessing the file. Since close()
"frees" that integer from the file descriptor table, the parent should not have any way to reference the file.
Is this the case? It seems very unlikely that this is the actual case, since it would cause FDs between parents and children to be very difficult to use (especially since you do not know which process will run first). So if this logic is incorrect, are the FDs duplicated on fork()
? How in the file descriptor table are the parent and child Fds related, especially between close()
calls? It helps me a lot to be able to draw out the file descriptor table, so I would like as specific as an answer as possible.
Thanks for any help with this!