在C中创建具有相同父级的三个子级

时间:2016-03-02 12:58:34

标签: c linux fork parent-child

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

#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

1 个答案:

答案 0 :(得分:3)

来自man fork:

  

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

您的if - else条件已被换掉。

相关问题