简体   繁体   中英

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?

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
}

You can use fork 3 times, but you got to make sure the fork gets only called from the parent process.

The easiest way to do that is to make sure the child won't ever escape its {} block.

if((pid = fork())<0) /*handle error*/;
if(pid == 0){
   //do child stuff

   exit(0); //the child must not escape this {} block
}
//do parent stuff

waitpid(2) is simple.

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