1

我正在用 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;
}
4

0 回答 0