syedify syedify - 5 months ago 8
Linux Question

Unable to join multiple fork()ed processes with wait()

I am trying to call multiple processes to do a task using

fork()
. I cannot seem to figure out how to call
wait()
on the parent process such that all the other processes go to completion. This code leads to the the app waiting forever.

int main () {
int i;
int status;

int nChildren = 100;
for(i = 1; i <= nChildren; i++){
pid = fork();
if(pid == 0){
printf("I'm a child: %d PID: %d\n",i, getpid());
childlabour();
}else if(pid == -1){
printf("Error exiting... \n ");
exit(1);
}
}
while (nChildren>0){
wait(&status);
nChildren--;
}

}





[EDIT] I have added the
_exit()
after
childlabour()
runs but now I seem to overwrite the data put in the buffer from previous processes i.e. data added by child (n-1) is overwritten by data added by child (n).

for(i = 1; i <= nChildren; i++){
pid = fork();
if(pid == 0){
printf("I'm a child: %d PID: %d\n",i, getpid());
childlabour();
_exit(2);
}else if(pid == -1){
printf("Error exiting... \n ");
exit(1);
}
}

Answer

Just add an _exit after childlabour:

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

void childlabour(){ printf("Child %d is labouring\n", getpid()); }
int main () {
    int i;
    int status;
    pid_t pid;

    int nChildren = 100;
    for(i = 1; i <= nChildren; i++){
        pid = fork();
        if(pid == 0){     
            printf("I'm a child: %d PID: %d\n",i, getpid());
            childlabour();
            _exit(0);
        }else if(pid == -1){
            printf("Error exiting... \n ");
            exit(0);
        }
    }
    while (nChildren>0){
        wait(&status);
        nChildren--;
    }
    puts("DONE");

}

or _Exit, or possibly even exit or return but the latter two only work in certain cases.