【问题标题】:Creating three children in C that have the same parent在 C 中创建三个具有相同父级的子级
【发布时间】:2016-03-02 12:58:33
【问题描述】:

我的问题是孩子没有相同的父母并且没有正确显示,这是我的代码:

#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
   pid_t pid[3];

   pid[0] = fork();

   if(pid[0] == 0)
   {
   /* First child */
      pid[1] = fork();
      if(pid[1] == 0)
      {
         /* First child continued */
         printf("Hello, I'm the first child! My PID is : %d, My PPID is: %d", getpid(), getppid());
         sleep(1);
       }
       else
       {
          /* Second child */
          pid[2] = fork();

          if(pid[2] == 0)
          {
             /* Second child continued */
             printf("Hello, I'm the second child! My PID is : %d, My PPID is: %d", getpid(), getppid());
             sleep(1);
          }
          else
          {
             /* Third child */
             printf("Hello, I'm the first child! My PID is : %d, My PPID is: %d", getpid(), getppid());
             sleep(1);
           }
       }
   }
   else
   {
   /* Parent */
      sleep(1);
      wait(0);
      printf("Hello, I'm the parent! My PID is : %d, My PPID is: %d", getpid(), getppid());
   }
   return 0;
}

截至目前,当我运行程序时,我将在 bash 中将其作为输出,其中 bash 的 PID 为 11446:

>Hello, I'm the third child! My PID is: 28738, My PPID is: 28735
>Hello, I'm the first child! My PID is: 28742, My PPID is: 28738
>Hello, I'm the second child! My PID is: 28743, My PPID is: 28738
>Hello, I'm the parent! My PID is: 28753, My PPID is: 11446

如何让第一个孩子出现第一个,第二个孩子出现第二个,第三个孩子最后出现,并让所有孩子都拥有 PPID 28753

【问题讨论】:

  • 显然,您的第三个孩子正在创建 child1 和 child2。但是父母的 PID 与您孩子的父母不同。
  • 你听说过一种叫做循环的编程结构吗?这是一件很巧妙的事情,它允许您多次执行相同的操作,而无需复制和粘贴代码。
  • 如果你 fork 进程,它们会并行运行。如果没有某种明确的同步,或者至少将每个输出的输出延迟更大的数量,你就不能让它们以特定的顺序输出。
  • (如果你想让所有的孩子都拥有同一个父母,那么你必须将他们全部那个父母分叉。所写的代码有一个孩子叉另一个)。

标签: c linux fork parent-child


【解决方案1】:

来自 man fork:

返回值
成功时,父进程返回子进程的 PID,子进程返回 0。失败时,-1 返回 父进程,没有创建子进程,并且设置了errno 适当的。

您的if-else 条件已交换。

【讨论】:

  • @davmac 谢谢。是的,但其他事情都搞砸了,就像孩子创造其他孩子一样。我希望这个提示答案可以帮助 OP 更好地可视化正确的代码。
猜你喜欢
  • 2013-10-22
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
  • 2014-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多