clinuxsystem-callsdup2vfork

Can I call dup2 after vfork?


I want to vfork() a child process, but have its stdout be different than the parent's stdout.

The obvious way to achieve this with fork() would be to dup2() (and close() the original file descriptor) in the child after forking.

Let's say I have the file descriptor ready before calling vfork() and just need to call these two system calls before calling an exec*() function. Am I allowed to do that?


Solution

  • My answer is probably yes.

    Based on Linux manual, A call to vfork() is equivalent to calling clone(2) with flags specified as:

            CLONE_VM | CLONE_VFORK | SIGCHLD 
    

    Note from clone(2):

    CLONE_FILES (since Linux 2.0) If CLONE_FILES is set, the calling process and the child process share the same file descriptor table. Any file descriptor created by the calling process or by the child process is also valid in the other process. Similarly, if one of the processes closes a file descriptor, or changes its associated flags (using the fcntl(2) F_SETFD oper‐ ation), the other process is also affected.

              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. 
    

    So after vfork, file operations in child process are isolated by default.