How to call fork multiple times C

1 Answer

0 votes
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>

int main() {
    int id1 = fork();
    int id2 = fork();
    
    if (id1 == 0) {
        if (id2 == 0) {
            printf("process a\n");
        } else {
            printf("process b\n");
        }
    } else {
        if (id2 == 0) {
            printf("process c\n");
        } else {
            printf("parent process\n");
        }
    }
    while (wait(NULL) != -1 || errno != ECHILD) {
        printf("wait for child process to finish\n");
    }

    return 0;
}




/*
run:

process c
process a
process b
wait for child process to finish
parent process
wait for child process to finish
wait for child process to finish

*/

 



answered Jan 5, 2021 by avibootz

Related questions

2 answers 246 views
1 answer 149 views
2 answers 184 views
1 answer 171 views
1 answer 207 views
1 answer 100 views
...