简体   繁体   中英

Wait for all child processes in fork chain

i want one parent process to create 10 child processes, but how can i make the parent process to wait for all child processes?

i have this given code in C

    for(int cnt = 1; cnt<=10; cnt++) {
        switch ( pid = fork() ) {
                case -1:
                    perror("error");
                    break;
                case 0:
                    printf("%d: child process, my PID=%d and PPID=%d\n", cnt, getpid(), getppid() );
                    sleep(10);
                    exit(0);
                break;
                default:
                    printf("%d: parent process, my PID=%d and PPID=%d\n", cnt, getpid(), getppid() );
                    sleep(10);
        }   
    }
}       

i tried with wait and waitpid in the default part, but it seems that the parent process only waits for the next child process to exit. how can i make it wait for all 10 child processes to exit?

You have to loop over the child processes and, if you want, get your status.

Like this:

int i, pid, status;
for (i=0; i<10N; i++) {
    pid=wait(&status);
    printf("Arrived child with pid %d - status %d\n", pid, status);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM