Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File descriptors before fork()

I know that if I call the open function before the fork(), the IO pointer is shared between the processes.

If one of these processes closes the file calling the close(fd) function, will the other processes still be capable to write/read the file or will the file be closed for everyone?

like image 679
rickyalbert Avatar asked Dec 24 '22 17:12

rickyalbert


2 Answers

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.

From fork() manual:

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)).

From close() manual:

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.

like image 181
P.P Avatar answered Dec 27 '22 07:12

P.P


Whenever a child process is created, it gets a copy of the file descriptor table from the parent process. And there is a reference count corresponding to each file descriptor, that is the number of processes currently accessing the file. So, if a file is open in master process and a child process is created, the reference count increments, as it is now open in child process as well, and when it is closed in any of the processes, it decrements. A file is finally closed when the reference count reaches zero.

like image 35
mandavi Avatar answered Dec 27 '22 05:12

mandavi