Search code examples
cparent-childwaitexit-codewaitpid

wait() does not wait for every child


I have a loop that creates 'n' child processes. The processes go into a separate program and sleep for 'x' seconds then return with exit status 'x'. The issue is when I try to wait for each individual process. It seems that my wait() call wait for the last made process and then the program exits. I would like it so that which ever child exits I can print their information and then wait for the next child to exit and print their information...and so on.

code:

int main()
{
      char input[12];
      int n, i, ch;
      pid_t pid;
      int status={0};

      printf("Enter an integer: ");
      fgets(input, 12, stdin);
      if (input[10] == '\n' && input[11] == '\0') { while ( (ch = fgetc(stdin)) != EOF && ch != '\n'); }
      rmnewline(input);

      n = atoi(input);

      for(i=0; i<=n-1; i++)
      {
      pid = fork();
      if(pid == 0)
        execl("/home/andrew/USP_ASG2/sleep", "sleep", NULL);
      }

      for(i=0; i<=n-1; i++)
      {
        wait(&status);
        if(WIFEXITED(status))
        {
          int exitstat = WEXITSTATUS(status);
          printf("Child %d is dead with exit status %d\n", pid, exitstat);
        }
      }
}

output:

In child 15930
In child 15929
In child 15928
Child 15930 is dead with exit status 5
Child 15930 is dead with exit status 5
Child 15930 is dead with exit status 5

Solution

  • You forget to capture the return value of wait(), so pid still contains the pid of the last process you forked off.

    Do this:

    pid = wait(&status);
    

    And you'll get the expected output.