1
votes

I am trying to fork() 10 child processes in one loop and then in another loop wait() for them to terminate and print their PID along with their exit status code. It cannot be done any other way or using any other function. Two loops/waves and the function wait(); This is what I have tried:

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    pid_t wait_p, p[10], p_child;
    int status;
    for (int i = 0; i < 10; i++)
    {
        p[i] = fork();
    }

    for (int i = 0; i < 10; i++)
    {
        switch (p[i])
        {
        case 0:
            p_child = getpid();
            exit(p_child % 10);
            break;
        case -1:
            puts("ERROR");
            break;
        default:
            wait_p = wait(&status);
            printf("Child with PID: %d", wait_p);
            if (WIFEXITED(status))
                printf(" terminated with STATUS: %d\n", WEXITSTATUS(status));
            break;
        }
    }

    return (EXIT_FAILURE);
}

This code will execute an endless count of child processes. It must print only the first original(issued by THE one parent) 10. What am I doing wrong?

1
Your main forks 10 processes before it checks to see it it's a child process. Move the 10 forks into the switch in the case 0 logic. - nicomp
thanks for your answer. I have to fork them in one loop and then wait for them to finish in another. - Mister Tusk
You create 1024 processes in the first loop — two to the power of ten. - Jonathan Leffler

1 Answers

1
votes

You have to handle the child processes directly in your first loop:

for (int i = 0; i < 10; i++)
{
    p[i] = fork();
    if (p[i] == 0) {
        p_child = getpid();
        exit(p_child % 10);
    } else if (p[i] == -1) {
            perror("fork");
    }        
}

and then wait for them in the second loop

for (int i = 0; i < 10; i++)
{       
        wait_p = wait(&status);
        printf("Child with PID: %d", wait_p);
        if (WIFEXITED(status))
                printf(" terminated with STATUS: %d\n", WEXITSTATUS(status));
}

You cannot handle the case, that fork() returns in the child process (yielding 0 as return value), in your second loop, otherwise each child process in the first loop keeps forking more child processes.