Skip to content
Advertisement

Creating three children in C that have the same parent

My problem is that the children does not have the same parent and does not appear correctly, here is my code:

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

As of right now when i run the program i will get this as output in bash, where bash has the PID of 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

How do i get the first child to appear first, second child to appear second and the third child to appear last, and get all the children to have the PPID 28753

Advertisement

Answer

From 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.

Your ifelse conditions are swapped.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement