Jason
Jason

Reputation: 1613

use wait to wait after all process finished but strange output

I want to do some thing with four parallel process

I first fork onec, and in child and parent fork again to get 4 process.

What I want is do something after all the 4 process finished, so I use the waitpid(-1, &status, 0);

and my ideal output is that

in

numbers

out

but the actual output may sometimes be

in

numbers

out

one number

and I cannot figure it out.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <error.h>

int main()
{
    pid_t cpid, w;
    int status;

    printf("%s\n", "in");
      cpid = fork();
      if (cpid == 0)
      {
          cpid = fork();
          if (cpid == 0)
          {
            printf("%s\n", "1");
            exit(EXIT_SUCCESS);
          }
          else{
            printf("%s\n", "2");
            exit(EXIT_SUCCESS);
          }
      }
      else{
          cpid = fork();
          if (cpid == 0)
          {
            printf("%s\n", "3");
            exit(EXIT_SUCCESS);
          }
          else{
              printf("%s\n", "4");
              //exit(EXIT_SUCCESS);
          }      
      }
      waitpid(-1, &status, 0); 
      printf("%s\n", "out");
      //do something
      exit(EXIT_SUCCESS);
    return 0 ;
}

Upvotes: 0

Views: 96

Answers (2)

Parthiban
Parthiban

Reputation: 2330

Better way to handle your scenario is by having signale handler for "SIGCHLD" in your main process and use wait/waitpid to obtain the child exit case. In such case, all your child death can be monitored/notified, as the SIGCLD will delivered to the main process.

Upvotes: 0

ravi
ravi

Reputation: 928

You are using waitpid() with pid=-1. It waits for any child process to finish. That means, as soon as any one of the child process finishes, the parent process's waitpid() will exit. It will not wait for any other child process to complete.

Upvotes: 2

Related Questions