Question

So I have a to make a function that takes in an argument n which is an int representing the number of children to be forked, and will print the pid of all the children that have been forked. So the goal of this function is to fork n children and each child prints out its pid. I am new to forking and not sure how to accomplish such a task.

Thank you in advance for any help you provide :)

This is what i have now, it seems to be working, but the program never ends once its finished. What should I do

 void print_child_pid(int n) {
int i;
pid_t pid; 
for (i = 1; i <= n; i++) {
    pid = fork();
    if (pid == -1) {
        /* error handling here, if needed */
        return;
    }
    if (pid == 0) {
        printf("child: process id = %d\n", getpid());
        wait();
        return;
    }
}

return; 

}

Was it helpful?

Solution

You are close but you are calling wait in the child process when you should be calling waitpid in the parent process. There is a nice explanation of this on wikipedia. I've modified your code below to use it.

void print_child_pid(int n) {
    int i;
    pid_t pid; 
    for (i = 1; i <= n; i++) {
        pid = fork();
        if (pid == -1) {
            /* error handling here, if needed */
        }
        if (pid == 0) {
            printf("child: process id = %d\n", getpid());
            return;
        }else{
            int status;
            (void)waitpid(pid, &status, 0);
        }
    }
}

Output with n = 4:

child: process id = 9363
child: process id = 9364
child: process id = 9365
child: process id = 9366
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top