我正在用MPI编写一个C ++程序,它将在MPI节点上启动外部程序。为此,我使用fork()/ execv()。
问题是,如果使用大量CPU(nCPU> 48),过程会正常启动,但会在某些时候冻结。我有理由相信问题是由使用fork()/ execv()的方法引起的。
代码:
int execute (char *task) {
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
pid_t child_pid;
int status;
if ((child_pid = fork()) < 0) {
cout << "Warning: fork failure on Node#" << world_rank << " with task " << task << endl;
perror("Warning (fork failure)");
exit(1);
}
if (child_pid == 0) {
//Execute on child thread
//Prepare command line arguments as a null-terminated array
std::vector<char*> args;
char* tasks = strtok(task, " ");
while(tasks != NULL) {
args.push_back(tasks);
tasks = strtok(NULL, " ");
}
args.push_back(NULL);
//Execute program args[0] with arguments args[0], args[1], args[2], etc.
execv(args[0], &args.front());
//Print on failure
cout << "Warning: execl failure on Node#" << world_rank << " with task " << task << endl;
perror("Warning (execl failure)");
_exit(1);
}
else {
//Parent process - wait for status message
wait(&status);
}
//Return status message
return status;
}
已解决(至少它看起来像......)
我修改了我的代码以实现vfork()而不是fork(),现在一切正常。注意,当vfork()返回到子进程时,它必须紧跟execve或_exit。
代码:
int execute (char *task) {
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
pid_t child_pid;
int status;
//Prepare command line arguments as a null-terminated array
std::vector<char*> args;
char* tasks = strtok(task, " ");
while(tasks != NULL) {
args.push_back(tasks);
tasks = strtok(NULL, " ");
}
args.push_back(NULL);
if ((child_pid = vfork()) < 0) {
exit(1);
}
//Child process
if (child_pid == 0) {
// !!! Since we are using vfork the child process must immediately call _exit or execve !!!
// !!! _Nothing_ else should be done in this part of the code to avoid corruption !!!
//Execute program args[0] with arguments args[0], args[1], args[2], etc.
execve(args[0], &args.front(), NULL);
_exit(1);
}
//Parent process
else {
//Wait for child process
wait(&status);
}
//Return status message
return status;
}