SunAns
SunAns

Reputation: 313

Multiple children of a single parent process

How do I use the waitpid() command here to wait for termination of its children and then show the PIDs.

for(int i=0; i < 5 ;i++)
{
    if(pid > 0)
    {
        pid = fork();
        c++;

        if(pid==0)
        {
            printf("child: %d \n",c);
            printf("child process with pid self %d \n", getpid());              


         }

    }
}

Upvotes: 2

Views: 1735

Answers (1)

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43558

You should refactor your loop like this:

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
...
pid_t pid;

for (int i = 0; i < 5; i++) {
    pid = fork();

    if (pid == 0) {
        printf("child process with pid %d\n", getpid());
        ...
        exit(0);
    } else if (pid > 0) {
        /* the child has been forked and we are in the parent */
    } else {
        /* could not fork child */
    }
}

int status;

while ((pid = waitpid(-1, &status, 0))) {
    if (pid == -1 && errno == ECHILD) {
        break;
    } else if (pid == -1) {
        perror("waitpid");
    } else if (WIFEXITED(status)) {
        printf("%d exited, status=%d\n", pid, WEXITSTATUS(status));
    } else if (WIFSIGNALED(status)) {
        printf("%d killed by signal %d\n", pid, WTERMSIG(status));
    } else if (WIFSTOPPED(status)) {
        printf("%d stopped by signal %d\n", pid, WSTOPSIG(status));
    } else if (WIFCONTINUED(status)) {
        printf("%d continued\n", pid);
    }
}

Note the inclusion of a call to exit at the end of the child block. This is needed in order to prevent the child from continuing the execution of the loop.

The second loop should run until all of the children have terminated.

Upvotes: 4

Related Questions