fork()时文件描述符是否共享?

26

假设我用open()打开一个文件,然后fork()我的程序。

父进程和子进程现在会共享文件描述符的相同偏移吗?

我的意思是如果我在父进程中进行写操作,那么在子进程中偏移量也会改变吗?

还是说fork()后偏移量将是独立的?

2个回答

32

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

1
这不取决于文件在哪里打开吗?也就是说,如果在 fork 之后或之前调用 open(filename, int..) 函数。 - ArmenB
3
那听起来像是一个内核漏洞。 - Ignacio Vazquez-Abrams
1
文件描述符1也会发生这种情况吗?它应该是标准输出(STDOUT)吗? 我的派生进程会共享标准输出吗? - Guillermo
@IgnacioVazquez-Abrams这是否意味着即使一个子进程打开了文件,它们也会共享同一个文件? - Dejell
1
@Dejell:fork()会导致子进程继承一些父进程的结构。如果没有父子关系,那么... - Ignacio Vazquez-Abrams
显示剩余3条评论

5
他们共享相同的偏移量。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接