我可以在vfork之后调用dup2吗?

时间:2017-11-01 13:48:02

标签: c linux system-calls dup2 vfork

我想vfork()一个子进程,但其stdout与父进程stdout不同。

使用fork()实现此目标的显而易见的方法是在分叉后,将dup2()(和close()原始文件描述符)放在子项中。

假设我在调用vfork()之前准备好了文件描述符,只需要在调用exec*()函数之前调用这两个系统调用。我被允许这样做吗?

1 个答案:

答案 0 :(得分:0)

我的回答可能是。

基于Linux手册,对vfork()的调用等效于使用指定为以下标志的调用clone(2):

        CLONE_VM | CLONE_VFORK | SIGCHLD 

克隆(2)的注释:

CLONE_FILES(从Linux 2.0开始)               如果设置了CLONE_FILES,则调用进程和子进程共享相同的文件描述符表。由调用过程或子进程创建的任何文件描述符               流程在其他流程中也有效。同样,如果其中一个进程关闭文件描述符或更改其关联标志(使用fcntl(2)F_SETFD操作符-               ),其他过程也会受到影响。

          If  CLONE_FILES  is not set, the child process inherits a copy of all file descriptors opened in the calling process at the time of clone().  (The duplicated file descrip‐
          tors in the child refer to the same open file descriptions (see open(2)) as the corresponding file descriptors in the calling process.)  Subsequent operations that open or
          close file descriptors, or change file descriptor flags, performed by either the calling process or the child process do not affect the other process. 

因此,在vfork之后,默认情况下会隔离子进程中的文件操作。