一个父母有2个子进程

时间:2014-01-04 00:16:22

标签: c fork parent-child

我正在尝试使用2个子项创建单个父进程。当我运行我的代码时,我得到3个不同的子进程ID。

      int main ()
{
pid_t child_pid, child_pid1;

printf("the main program process ID is %d\n", (int) getpid());

child_pid = fork ();
if (child_pid != 0)
{
    printf(" the parent process ID is %d\n", (int) getppid());
    printf(" the child's process ID is %d\n", (int) child_pid);
}

child_pid1 = fork ();
if (child_pid1 != 0)
{
    printf(" the child's process ID is %d\n", (int) child_pid1);
}

return 0;
 }

2 个答案:

答案 0 :(得分:2)

该行:

child_pid1 = fork ();

正在由原始进程和第一个子进程执行。因此,您最终得到一个父级,它创建了两个子进程,第一个进程也创建了一个子进程。

试试这样:

int main ()
{
pid_t child_pid, child_pid1;

printf("the main program process ID is %d\n", (int) getpid());

child_pid = fork ();
if (child_pid != 0)
{
    printf(" the parent process ID is %d\n", (int) getppid());
    printf(" the child's process ID is %d\n", (int) child_pid);
    child_pid1 = fork ();
    if (child_pid1 != 0)
    {
        printf(" the child's process ID is %d\n", (int) child_pid1);
    }
}


return 0;
}

答案 1 :(得分:0)

当我运行你的程序时,我得到类似下面的内容(为了解释目的而添加破折号之前的部分):

1 (MAIN) - the main program process ID is 30583
2 (PARENT OF MAIN) - the parent process ID is 15915
3 (FIRST FORK) - the child's process ID is 30584
4 (FORK OF MAIN) - the child's process ID is 30585
1 - the main program process ID is 30583
2 - the parent process ID is 15915
3 - the child's process ID is 30584
1 - the main program process ID is 30583
5 (FORK OF FIRST FORK) - the child's process ID is 30586
1 - the main program process ID is 30583

您所看到的实际上是 5个流程

当然,标记为“1”的过程是主要过程,但三个来自叉子!基本上,第一个fork从主进程创建两个进程。第二个fork被调用两次(因为每个进程现在都在该点运行)所以它创建了两个进程。现在,标记为“2”的进程实际上是主进程的父进程,这就是为什么在输出中有五个不同的进程ID的原因。

编辑 - 我标记了叉子的“名称”,以便您可以看到每个来自哪里。希望有所帮助!