Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ fork() -- creating a "list" of processes

Tags:

c++

fork

I have a program that creates new processes "one by one". Is it possible to change this code so it creates a "list" of processes – i.e. child 1 being the parent of child 2, child 2 being the parent of child 3, etc.?

#include <string>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "err.h"

using namespace std;
int main ()
{
 pid_t pid;
 int i;

 cout << "My process id = " << getpid() << endl;

 for (i = 1; i <= 4; i++)
  switch ( pid = fork() ) {
  case -1:
    syserr("Error in fork");

  case 0:
    cout << "Child process: My process id = " << getpid() << endl;
    cout << "Child process: Value returned by fork() = " << pid << endl;
    return 0;

  default:
    cout << "Parent process. My process id = " << getpid() << endl;
    cout << "Parent process. Value returned by fork() = " << pid << endl;

   if (wait(NULL) == -1) 
   syserr("Error in wait");

 }  
 return 0;
 }
like image 832
user2262230 Avatar asked Jun 03 '13 05:06

user2262230


1 Answers

If you want to keep the loop in order to dynamically set the depth of the fork tree,

// Set DEPTH to desired value

#define DEPTH 4

int main ()
{
  pid_t pid;
  int i;

  cout << "My process id = " << getpid() << endl;

  for (i=1 ; i <= DEPTH ; i++) {

    pid = fork();    // Fork

    if ( pid ) {
       break;        // Don't give the parent a chance to fork again
    }
    cout << "Child #" << getpid() << endl; // Child can keep going and fork once
  }

  wait(NULL);        // Don't let a parent ending first end the tree below
  return 0;
}

Output

My process id = 6596
Child #6597
Child #6598
Child #6599
Child #6600
like image 190
Déjà vu Avatar answered Sep 19 '22 21:09

Déjà vu