Search code examples
c++forkwaitpid

Forking and Waiting


I am trying to create a fan of processes via forking. I want 1 process to be the base of the fan, and all other processes to fork from the base(all processes have the same parent, P1 is parent to P2, P3, P4, ...).

I have gotten this part down just fine. My real problem lies with waiting for the parent process(I think) to finish making children. Here is my code below:

//Create fan of processes
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int main()
{
  pid_t pid;
  cout << "Top Parent: " << getpid() << endl;
  for ( int i = 0; i < 9; ++i ) {
    pid = fork();
    if ( pid ) { //parent process
        continue;
    } else if ( pid == 0 ) {
        cout << "Child: (" << getpid() << ") of Parent: (" << getppid() << ")" << endl;
        break;
    } else {
        cout << "fork error" << endl;
        exit( 1 );
    }
  }
}

Guess I need some help on getting the output to behave itself as this is what it looks like:

Top Parent: 6576
Child: (6577) of Parent: (6576)
Child: (6581) of Parent: (6576)
Child: (6583) of Parent: (6576)
Child: (6579) of Parent: (1)
[remoteuser@server folder]$ Child: (6585) of Parent: (1)
Child: (6584) of Parent: (1)
Child: (6582) of Parent: (1)
Child: (6580) of Parent: (1)
Child: (6578) of Parent: (1)

Solution

  • You should wait until all the child completes their tasks put following code in parent side.

       printf("Parent process started.n");
            if ((pid = wait(&status)) == -1)
                                         /* Wait for child process.      */                                   */
               perror("wait error");
            else {                       /* Check status.                */
               if (WIFSIGNALED(status) != 0)
                  printf("Child process ended because of signal %d.n",
                          WTERMSIG(status));
               else if (WIFEXITED(status) != 0)
                  printf("Child process ended normally; status = %d.n",
                          WEXITSTATUS(status));
               else
                  printf("Child process did not end normally.n");
            }
            printf("Parent process ended.n");