了解以非阻塞方式等待子进程的可重入父函数

时间:2017-06-24 19:50:42

标签: process fork c++14 nonblocking waitpid

我在Linux上运行了一些C ++代码,其中重入,bool返回,父进程分叉子进程(当然只有一次),然后使用waitpid检查所述子进程的退出状态。如果子进程完成,则它返回到父进程,然后子进程退出,然后父进程看到此退出状态并返回true(然后转到其他代码)。

否则,如果子进程仍在运行,父进程也将看到这一点并返回false,然后一遍又一遍地调用父进程,直到子进程完成并退出。

换句话说,父进程使用WNOHANG调用waitpid,从而以非阻塞方式等待子进程。

术语“等待”在这里有点用词不当,因为父函数在返回之前不等待孩子完成;但是,在孩子完成之前,父母不会停止被叫。

如下所示:

main()
{
    while(status != true)
    {
        status = funcThatCallsFork();
    }
    // child completed and parent saw exit status and is moving on now
}

bool funcThatCallsFork()
{
    //if first pass
    fork()

    //child code (pid == 0)
    {
        funcThatChildCalls();
        _exit(); // child exits as soon as it returns from call
    }

    //else not first pass
    //check waitpid with WNOHANG for status change of child

    //if child exited return true, else return false 
}

funcThatChildCalls()
{
    // do time consuming stuff

    // return
}

我的问题是,由于子进程是在父进程帧#1上生成的,并且在子进程完成时,父进程现在将在某个帧#(1 + n)上;那么子进程如何知道返回当前的父进程帧,而不是生成它的父进程帧(即:帧#1)?实际上,它确实基于我所执行的测试;只是想了解原因。

感谢您的时间!

0 个答案:

没有答案
相关问题