0

I want to create multiple processes from one master process. I know I want to use a function from the exec family, but it does not seem to be preforming in the way I intended it to. It seems that exec() is a blocking call, or maybe I am just using it wrong. Anyway, on to the code:

const char* ROUTERLOCATION = "../../router";
int main(int argc, char** argv) {
  manager manager;
  vector<string> instructions = manager.readFile(argv[1]);
  ...
  //file gives me the number of proceses i want to spawn and that value goes in 
  //rCount
  for(int i = 0; i < rCount; i++){
    cout << "creating:" << i << endl;
    execl(ROUTERLOCATION, "",NULL);
    }
}

The output I see is:

creating:0
HI!!!

And then everything exits gracefully. Can I not spawn more than one process using execl()?

Also, I would like to communicate with each of these processes, so I don't want to be blocking while these processes are running.

aschepler
  • 70,891
  • 9
  • 107
  • 161
nook
  • 2,378
  • 5
  • 34
  • 54
  • 1
    Where is the `fork` call? You need to call that, and if it indicates you are the child process you do the `exec`. The parent continues running and forking children. The children all replace themselves with the program you want to run. – paddy Oct 26 '12 at 02:53

2 Answers2

2

You need to fork in your master process, the in your child processes call execl. (exec family of functions replaces your current process image with your new process, so hence why your for loop never completes.)

hexist
  • 5,151
  • 26
  • 33
  • if I fork in the master, won't all my children then read the file as well? – nook Oct 26 '12 at 03:00
  • I don't know what your readFile does, but if it just reads the file then closes it and returns the results, then if you fork after that (right before your execl), then no it wont re-read the file, execution proceeds from the point at which you fork. Your child will have a copy of everything the parent does though, at least until execl is called (then everything gets replaced.) – hexist Oct 26 '12 at 03:05
  • 1
    You are correct. Thanks. accepting you as you were the first. Thanks so much. – nook Oct 26 '12 at 03:10
1

calling exec() means that your current program not longer exists. You might want to create a new process using fork() and then call exec() in it so that exec() replaces your new process and your main process still works as you intend it to.

example:

pid_t pid = fork();
if (pid == 0) {// child
    execl();
} else { // parent
}
aakash
  • 751
  • 5
  • 18