so i fork n process:

for(i=0; i<numOfProcess; i++)
    pid == fork();
    if(pid == -1)
        //error handling
    if(pid == 0){
        //child, do something
        exit(0);
    }
    else{ //parent
        //i want to wait till all children are done before continue..how?
        //i tried wait(NULL), and waitpid(pid, NULL, 0)
        //but both wont work..?

    //...........
    //something done in parent
    }

This works. You have to wait for all started.

#include <sys/types.h>
#include <sys/wait.h>
#include <cstdlib>
#include <iostream>
#include <unistd.h>
using namespace std;

int main(){
  int pid,i,numOfProcess(10);

  for(i=0; i<numOfProcess; i++){
    pid = fork();    // <-------- You had a == not = 
    if(pid == -1){   // <-------- You didn't have a open {, close }
        //error handling
    }
    else if(pid == 0){
        //child, do something
        cout << "Child " << i << " sleeping(" << i << ")" << endl;
        sleep(i);
        exit(0);
    }
    else{ //parent
        //i want to wait till all children are done before continue..how?
        //i tried wait(NULL), and waitpid(pid, NULL, 0)
        //but both wont work..?
      cout << "Started proc(" << i << ")" << endl;
    //...........
    //something done in parent
    }
  }
  cout << "Waiting" << endl;
  // Need to wait for all
  for(i=0; i<numOfProcess; i++){
    wait(NULL);
    cout << "Got " << i+1 << " done" << endl;
  }
  return 0;  
}

Output

$ ./a.out
Started proc(0)
Started proc(1)
Started proc(2)
Started proc(3)
Started proc(4)
Started proc(5)
Started proc(6)
Started proc(7)
Started proc(8)
Started proc(9)
Waiting
Child 6 sleeping(6)
Child 4 sleeping(4)
Child 8 sleeping(8)
Child 2 sleeping(2)
Child 0 sleeping(0)
Got 1 done
Child 5 sleeping(5)
Child 7 sleeping(7)
Child 9 sleeping(9)
Child 3 sleeping(3)
Child 1 sleeping(1)
Got 2 done
Got 3 done
Got 4 done
Got 5 done
Got 6 done
Got 7 done
Got 8 done
Got 9 done
Got 10 done
$

Edited 4 Years Ago by histrungalot: Added more

This article has been dead for over six months. Start a new discussion instead.