26

Let's say I open a file with open(). Then I fork() 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()?

2 Answers 2

32

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)).
8
  • 1
    Doesn'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
    Dec 13, 2012 at 18:48
  • The 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
    – ArmenB
    Dec 14, 2012 at 17:29
  • 3
    That... sounds like a kernel bug. Dec 14, 2012 at 17:30
  • 1
    Is going to also happend with file descriptor 1, that is suppose to be the STDOUT? Is my forked process going to share the stdout?
    – Guillermo
    Aug 21, 2013 at 10:22
  • 1
    @Dejell: fork() causes children to inherit certain of their parent's structures. If there is no parent/child relationship, then... Dec 4, 2017 at 18:13
5

They do share the same offset.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.