Are file descriptors shared when fork()ing?
12,685
Solution 1
From fork(2)
:
* The child inherits copies of the parent’s set of open file descrip- tors. 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)).
Solution 2
They do share the same offset.
Related videos on Youtube
Author by
Delimitry
Software engineer, contributing PSF member My blog: Delimitry
Updated on May 10, 2022Comments
-
Delimitry almost 2 years
Let's say I open a file with
open()
. Then Ifork()
my program.Will father and child now share the same offset for the file descriptor?
I mean if I do a write in my father, the offset will be changed in child too?
Or will the offsets be independent after the
fork()
? -
ArmenB over 11 yearsDoesn't this depend where the file has been opened? Meaning if the open(filename, int..) call is made after the fork, or before it.
-
ArmenB over 11 yearsThe odd thing about this is, if the file open statement is made after the fork, then you have two different file descriptors. But when I try to lock the file using fcntl, it won't work. Both the child and the parent ignore the lock
-
Ignacio Vazquez-Abrams over 11 yearsThat... sounds like a kernel bug.
-
Guillermo over 10 yearsIs going to also happend with file descriptor 1, that is suppose to be the STDOUT? Is my forked process going to share the stdout?
-
Dejell over 6 years@IgnacioVazquez-Abrams will it be shared between children of the parent? if one child opens a file, will the other children share the same copy?
-
Dejell over 6 years@IgnacioVazquez-Abrams does that mean that they will all share the same file even if one child process opened it?
-
Ignacio Vazquez-Abrams over 6 years@Dejell:
fork()
causes children to inherit certain of their parent's structures. If there is no parent/child relationship, then... -
JakeD over 5 years@Dejell I had the same confusion, but as I understand this answer, only the files that are already open in the parent at the time of the fork call will be open in the child. So no future opening of files by either the parent or the child will be shared.