【问题标题】:One parent with 2 child processes一个父进程有 2 个子进程
【发布时间】:2014-01-04 00:16:22
【问题描述】:

我正在尝试创建一个包含 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;
 }

【问题讨论】:

  • 每个人都疯了!
  • 你怎么知道你有 3 个孩子?
  • @MadPhysicist;因为父母很清楚:)
  • 我会说我们应该在这个问题上坚持一个叉子,看看它是否完成! :)

标签: c fork parent-child


【解决方案1】:

行:

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;
}

【讨论】:

    【解决方案2】:

    当我运行你的程序时,我得到如下内容(破折号之前的部分已添加用于解释目的):

    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。

    编辑 - 我标记了叉子的“名称”,这样你就可以看到每个叉子的来源。希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2016-07-27
      • 1970-01-01
      • 2017-06-29
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多