Search code examples
cpipefork

Fork wait and pipe in C


I have this assignment where we are supposed to create a specific amount of child processes, lets say 3, and make the parent wait for each child to finish. Also we're supposed to have a pipe that all processes write to so that once the parent is done waiting, it would use the pipe's to output the sum of all the children's results.

This is my code so far but it seems that wait(NULL) isn't working as expected. I am not sure what I'm doing wrong.

#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main() {
  for (int i=0; i<3; i++) {
    pid_t child = fork();
    if (child > 0) {
      printf("Child %d created\n", child);
      wait(NULL);
      printf("Child %d terminated\n", child);
    }
  }

  printf("Parent terminated\n");
  return 0;
}

Solution

  • First of all, it's better to first run all child processes and then wait for all of them, instead of waiting for each one sequentially.

    In addition, the child processes should exit immediately and not keep running the forked code.

    Thirdly, you must pay attention and wait for all children after the loop, and not only for the first one that terminates:

    #include <stdio.h>
    #include <sys/wait.h>
    #include <unistd.h>
    
    int main() {
      for (int i=0; i<3; i++) {
        pid_t child = fork();
        if (child > 0) {
          printf("Child %d created\n", child);
        }
        else if (child == 0) {
          printf("In child %d. Bye bye\n", i);
          return 0; // exit the child process
        }
      }
    
      while (wait(NULL) > 0); // wait for all child processes
    
      printf("Parent terminated\n");
      return 0;
    }
    

    EDIT:

    The code above is just an improvement to the example given in the question. In order to implement the pipe of information from the child processes to the parent, a pipe can be created (using pipe()) and the write-end file descriptor would be accessible from child processes.

    Here's a good example to do so.