<分区>
我尝试使用 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()
开头的语句将在父进程中执行两次。