我有一个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分支,而不是1。有什么想法吗?
发布于 2009-08-06 13:13:49
那么,进程1将由第一个fork创建。进程2将由if语句中的fork创建。因此,为了让进程2也派生,如果第二个派生没有返回0,则在if -语句中再次派生。
下面是一个示例:
if(fork) {
// Inside process 0
if(fork) {
// still in process 0
} else {
// in process 2
if(fork) {
// still in process 2
} else {
// in prcess 3
}
// and so on
}
} else {
// Inside process 1
}发布于 2009-08-06 13:15:06
子节点获取父节点在分支时的状态的副本。
因此,如果父进程具有计数器或其他属性,则子进程将看到它们被派生时的值(但如果父进程随后更改了该值,则不会看到该值)。
发布于 2009-08-06 13:16:57
我不知道您为什么要这样做,但通常只有父进程执行分支。这可能也更容易设计。当您在for循环中执行fork()时,您将直接控制所创建的进程。
请注意,fork()是一个相对昂贵的操作,特别是当您想要创建许多进程时。还有更轻量级的vfork和线程可供选择,但我不能判断它们是否也适合您的需求。
https://stackoverflow.com/questions/1238711
复制相似问题