gpt4 book ai didi

c - 如果 shell 输出通过管道传输到某处,fork() 会导致父级 main 的开头执行

转载 作者:行者123 更新时间:2023-12-02 02:44:00 25 4
gpt4 key购买 nike

<分区>

我尝试使用 fork() 函数,但出现了一些奇怪的行为。父进程的部分(不是全部)主要函数似乎在 fork() 被调用后立即运行,但前提是可执行文件的输出通过管道传输到命令行中的某处。

我在 Mac OS Mojave 上注意到了这一点,但我在 Ubuntu 18.04 上测试了相同的代码,它表现出相同的行为。我不知道为什么会这样。

下面是fork.c文件中的测试代码:

#include <stdio.h>
#include <unistd.h>

int main(void)
{
pid_t child_pid;
printf("Beginning of main for process %d\n", getpid());
if ((child_pid = fork())) {
printf("Forked process %d\n", child_pid);
} else {
printf("Beginning of forked process %d\n", getpid());
}
}

这是一个使用这段代码的 shell session :

 $ cc fork.c
$ ./a.out
Beginning of main for process 98373
Forked process 98374
Beginning of forked process 98374
$ ./a.out | cat
Beginning of main for process 98378
Forked process 98380
Beginning of main for process 98378
Beginning of forked process 98380

正如您在上面看到的,如果输出通过管道传输到某处,则 main() 开头的语句将在父进程中执行两次。

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