Neil Bharat Patel
Neil Bharat Patel

Reputation: 135

Using Forks with waitpid

Are there 3 child processes and 1 parent process? What does the two different waitpid do, and why are there two of them?

int main()
{
    pid_t pid;

    int status, counter = 4;
    while(counter > 0)
    {
        pid = fork();
        if(pid)
        {
            counter /= 2;
        }
        else
        {
            printf("%d", counter); /* (1) */
            break;
        }
    }
    if(pid)
    {
        waitpid(-1, &status, 0);
        counter += WEXITSTATUS(status);
        waitpid(-1, &status, 0);
        counter += WEXITSTATUS(status);
        printf(";%d", counter); /* (2) */
    }
    return counter;
}

the second printf after the waitpid prints 3, 5, 6, 34, 52, 61 (excluding the semicolon). Im not sure how there are two digits printing. I know the second digit is probably coming from the printf in the while loop.

Upvotes: 0

Views: 1234

Answers (1)

jfs
jfs

Reputation: 414875

Yes, there are 3 child processes and 1 parent. Children return 4, 2, 1.

To collect all statuses, you could use a while loop:

if(pid)
{
  while (waitpid(-1, &status, 0) != -1) /* ignoring signals, errors */
    counter += WEXITSTATUS(status);
}
return counter;

Parent returns 7 in this case.

If you use only two waitpid() calls then they may return any pair from {4,2,1} set e.g., {4,1} or {2,1} so parent prints ;5 and ;3 correspondingly.

Due to stdio buffering and fork() interaction, the output may multiply. See printf anomaly after “fork()”

Either fflush() before fork() or use write/_exit in children instead.

Upvotes: 1

Related Questions