gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 12:40:23 27 4
gpt4 key购买 nike

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

使用 fork() 实现此目的的明显方法是 dup2()(和 close() 原始文件描述符)在 fork 后的 child 中。

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

最佳答案

我的回答可能是肯定的。

根据 Linux 手册,对 vfork() 的调用等同于使用指定的标志调用 clone(2):

        CLONE_VM | CLONE_VFORK | SIGCHLD 

来自克隆(2)的注释:

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

          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之后,子进程中的文件操作默认是隔离的。

关于我可以在 vfork 之后调用 dup2 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47056411/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com