I know that if I call the
open function before the fork() the IO pointer is shared between the processes.
My question is: if one of these processes closes the file calling the
close(fd) function, will the other processes be still capable of write/read the file or the file will be closed for everyone? Thanks
Best How To :
Yes. Each process has a copy of the file descriptor (among other things). So one process closing it won't affect the copy of the
fd in other process.
The child inherits copies of the parent's set of open file descriptors. Each file descriptor in the child refers to the same open file description (see open(2)) as the corresponding file descriptor in the parent. This means that the two descriptors share open file status flags, current file offset, and signal- driven I/O attributes (see the description of F_SETOWN and F_SETSIG in fcntl(2)).
If fd is the last file descriptor referring to the underlying open file description (see open(2)), the resources associated with the open file description are freed; if the descriptor was the last reference to a file which has been removed using unlink(2), the file is deleted.
So if you do
close(fd); it closes only the reference in that process and other process holding another reference to the same file descriptor can continue to operate on it.