C 如何等待子进程并获取其返回值

C 如何等待子进程并获取其返回值,c,linux,fork,waitpid,C,Linux,Fork,Waitpid,我正在尝试在嵌入式linux环境下运行我的C应用程序,并获取其失败/成功分析的返回值 我看了类似的问题(例如,和其他一些问答…),但仍然无法让它起作用 代码: (或带有信号)没有区别。 我可以成功地为SIGCHLD添加一个信号处理程序,并且可以使用sigwait()或类似的方法来等待信号,而不是子进程,但这似乎是一个糟糕的解决方案 你知道我错过了什么吗 $uname-mrso Linux 3.18.20 armv7l GNU/Linux 您的代码很好地测试了“错误”。好 但不幸的是,代码没有捕捉

我正在尝试在嵌入式linux环境下运行我的C应用程序,并获取其失败/成功分析的返回值

我看了类似的问题(例如,和其他一些问答…),但仍然无法让它起作用

代码:

(或带有信号)没有区别。 我可以成功地为SIGCHLD添加一个信号处理程序,并且可以使用sigwait()或类似的方法来等待信号,而不是子进程,但这似乎是一个糟糕的解决方案

你知道我错过了什么吗

$uname-mrso
Linux 3.18.20 armv7l GNU/Linux


您的代码很好地测试了“错误”。好

但不幸的是,代码没有捕捉到您要处理的案例,其中
waitpid()
实际上返回了孩子的PID

你可以这样做:

for (i = 0 ; i < 10 ; i++)
{
    pid_t ws = waitpid(pid, &childExitStatus, WNOHANG);
    if (-1 == ws)
    {
        DEBUG_PRINT("parent - failed wait. errno = %d", errno);
        return -1;
    }
    else if (0 == ws)
    {
        DEBUG_PRINT("parent - child is still running");
        sleep(1);
        continue;
    }

    DEBUG_PRINT("parent - successfully waited for child with PID %d", (int) ws);

    break;
}
(i=0;i<10;i++)的

{
pid_t ws=waitpid(pid和childExitStatus,WNOHANG);
如果(-1==ws)
{
调试\u打印(“父级-等待失败。错误号=%d”,错误号);
返回-1;
}
else如果(0==ws)
{
调试打印(“父-子系统仍在运行”);
睡眠(1);
继续;
}
调试_打印(“父级-已成功等待PID为%d的子级”,(int)ws);
打破
}

正确。太多的问答让我寻找太深的问题。谢谢
...
DEBUG_PRINT("forking");
signal(SIGCHLD,SIG_DFL);
pid = fork();
...
for (i = 0 ; i < 10 ; i++)
{
    pid_t ws = waitpid(pid, &childExitStatus, WNOHANG);
    if (-1 == ws)
    {
        DEBUG_PRINT("parent - failed wait. errno = %d", errno);
        return -1;
    }
    else if (0 == ws)
    {
        DEBUG_PRINT("parent - child is still running");
        sleep(1);
        continue;
    }

    DEBUG_PRINT("parent - successfully waited for child with PID %d", (int) ws);

    break;
}