【发布时间】:2009-08-06 13:00:47
【问题描述】:
我有一个如下所示的 C 文件:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main ()
{
pid_t child_pid;
printf ("The PID is %d\n", (int) getpid ());
child_pid = fork ();
if (child_pid != 0)
{
printf ("this is the parent process, with PID %d\n",
(int)getpid());
printf ("the child's PID is %d\n", (int) child_pid);
}
else
printf ("this is the child process, with PID %d\n",
(int)getpid());
return 0;
}
我需要修改它以生成一个看起来像这样的层次结构
parent (0)
|
+---> child (1)
|
+---> child (2)
|
+----> child (3)
|
+----> child (4)
|
+----> child (5)
|
基本上是一个树结构,其中每个第二个孩子产生两个新孩子。据我了解,当我fork()一个进程时,每个进程都会同时运行。在if 语句中添加fork() 似乎可以正常工作并正确创建进程0 到2,因为只有父进程会创建一个新的fork。但我不知道如何制作流程 2 的 fork 而不是 1。有什么想法吗?
【问题讨论】:
-
你考虑过这个过程的限制吗?什么时候停止,为什么?它将对操作系统做什么? (在 unix 派生系统上,请考虑阅读
ulimit的手册页。)只是想提供帮助。