【发布时间】:2014-04-08 20:53:42
【问题描述】:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main ()
{
pid_t child_pid;
printf ("the main program process ID is %d\n", (int) getpid());
child_pid = fork () ;
if (child_pid != 0)
{
printf ("this is the parent process, with id %d\n", (int) getpid ());
printf ("the child's process ID is %d\n",(int) child_pid );
}
else
printf ("this is the child process, with id %d\n", (int) getpid ());
return 0;
}
我编写了一个简单的 fork 程序来创建一个进程,当我运行该程序时,我得到如下输出:
the main program process ID is 3322
this is the child process , with ID 0
现在我的意思是,为什么 if 块没有像在父进程中那样执行,fork() 的返回值不等于 0 那么为什么我没有得到任何输出if 块?
【问题讨论】:
-
@Ishmeet 这不是 fork 的工作方式。
-
我刚刚在 Debian 7 和 Mac OSX 19.9 平台上对此进行了测试,它们都完全按照他们应该做的那样做。等待(NULL);在你的父块中只是为了踢。似乎您的父进程 io 在分叉后被重定向或压制。奇怪。
-
在 Red Hat Enterprise Linux 6 中对其进行了测试。它可以正常工作。你的结果确实很奇怪。您使用什么操作系统/版本和编译器/版本?
-
你的程序是这样运行的吗:
./a.out > out-file? -
首先我做了这个
gcc -o fork fork.c然后我做了这个./fork
标签: c unix operating-system fork