Search code examples
cprocessforkwaitpid

C - Create 3 child processes with fork()


I want to create exactly 3 child processes with fork(). Here is my code to create one child process:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

void main(){
    int pid = fork();
    if(pid < 0){
        /* was not successfully */
    }
    else if (pid > 0){
        /* Parent process */
    }
    else{
        /* Child process */
        for (int i = 0; i < 20; i++){
            printf("1");
            usleep(1000);
        }
        exit(0);
    }
}

The child process should print 20 times the number 1 and sleep 1 millisecond after every time.

I know I cant just use fork() 3 times, because then I will get 7 child processes. But how can I get exactly 3? And how can I do it, that every child process prints an other number? For example the first process the number 1, the second process number 2 and the third process number 3.

And the parent should use waitpid() to wait for all 3 children. And if they are finished the parent should print a message. But how can I use waitpid here?


Solution

  • for (int kid = 0; kid < 3; ++kid) {
        int pid = fork();
        if(pid < 0){
            exit(EXIT_FAILURE);
        }
        else if (pid > 0){
            /* Parent process */
        }
        else{
            /* Child process */
            exit(EXIT_SUCCESS);
        }
    }
    
    for (int kid = 0; kid < 3; ++kid) {
        int status;
        pid_t pid = wait(&status); // kids could be ready in any order
    }