获取子进程的返回值而不保留父执行

时间:2018-06-21 18:25:06

标签: c linux multithreading fork waitpid

我需要能够从子进程中获取返回的值,而不必保留父进程的执行。

请注意,子进程中可能会发生运行时错误。

这是我要制作的程序:

//In parent process:
do
{
    read memory usage from /proc/ID/status
    if(max_child_memory_usage > memory_limit)
    {
        kill(proc, SIGKILL);
        puts("Memory limit exceeded");
        return -5; // MLE
    }
    getrusage(RUSAGE_SELF,&r_usage);
    check time and memory consumption
    if(memory limit exceeded || time limit exceeded)
    {
        kill(proc, SIGKILL);
        return fail;
    }
    /*
    need to catch the returned value from the child somehow with
    this loop working.
    Notice the a runtime error could happen in the child process.
    */
while(child is alive);

2 个答案:

答案 0 :(得分:2)

waitpid函数具有一个名为WNOHANG的选项,如果给定的子代尚未返回,则该函数将立即返回:

pid_t rval;
int status;
do {
    ...

    rval = waitpid(proc, &status, WNOHANG);
} while (rval == 0);

if (rval == proc) {
    if (WIFEXITED(status)) {
        printf("%d exited normal with status %d\n", WEXITSTATUS(status));
    } else {
        printf("%d exited abnormally\n");
    }
}

有关检查各种异常退出条件的更多详细信息,请参见man page for waitpid

答案 1 :(得分:1)

使用WNOHANG标志的解决方案仅在您只需要检查一次孩子的退出状态时才有效。但是,如果您希望在子项退出时获取退出状态,那么无论多晚,最好的解决方案是为SIGCHLD信号设置信号处理程序。 当子进程正常或异常终止时,SIGCHLD将被发送到父进程。在此信号处理程序中,您可以调用wait来获得孩子的退出状态。

void child_exit_handler(int signo){

    int exit_status;

    int pid = wait(&exit_status);

    // Do things ...
}
// later in the code, before forking and creating the child
signal(SIGCHLD, child_exit_handler);

根据程序的其他语义,您可能需要使用waitpid。 (如果程序已停止但未终止,则也可能会调用SIGCHLD。wait(2)的手册页描述了要检查的宏。)

相关问题