execute multiple processes from a master process

六月ゝ 毕业季﹏ 提交于 2019-12-11 18:33:13

问题


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.


回答1:


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.)




回答2:


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
}


来源:https://stackoverflow.com/questions/13080093/execute-multiple-processes-from-a-master-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!