在 C 中创建三个具有相同 parent 的 children

Creating three children in C that have the same parent

我的问题是 children 没有相同的 parent 并且显示不正确,这是我的代码:

#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

如何让第一个 child 首先出现,第二个 child 第二个出现,第三个 child 最后出现,并获得所有 child ren 拥有 PPID 28753

来自 man fork:

RETURN VALUE
On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.

你的if-else条件被调换了。