gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:45:14 26 4
gpt4 key购买 nike

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

我查看了类似的问题(例如 thisthisthisthis 和其他一些 Q/A..),但仍然无法正常工作。

代码:

static int fork_test(const char *src, const char *dst)
{
int childExitStatus;
pid_t pid;
int status;

DEBUG_PRINT("forking");

pid = fork();

if (pid == 0) { // child
sleep(2);
DEBUG_PRINT("child - exiting");
exit(1);
}
else if (pid < 0) {
return -1;
}
else { // parent
int i;
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;
}
if (0 == ws)
{
DEBUG_PRINT("parent - child is still running");
sleep(1);
continue;
}
}
if (10 == i)
return -1;

DEBUG_PRINT("parent - done waiting");

if (WIFEXITED(childExitStatus)) /* exit code in childExitStatus */
{
DEBUG_PRINT("parent - got status %d", childExitStatus);
status = WEXITSTATUS(childExitStatus); /* zero is normal exit */
if (0 != status)
{
DEBUG_PRINT("parent - picked up bad exit status");
return status;
}
return 0;
}
else
{
DEBUG_PRINT("parent - bad exit route");
return -1;
}
}
}

这提供了这个输出:

forking
parent - child is still running
parent - child is still running
parent - child is still running
child - exiting
parent - failed wait. errno = 10

请注意,errno=10 表示 ECHILD。

所以我尝试添加:

...
DEBUG_PRINT("forking");
signal(SIGCHLD,SIG_DFL);
pid = fork();
...

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

知道我在这里遗漏了什么吗?

$ uname -mrso
Linux 3.18.20 armv7l GNU/Linux

最佳答案

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

但是不幸的是,代码没有捕捉到您想要的情况,waitpid() 实际上返回了 child 的 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;
}

关于c - 如何等待子进程并获取其返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48049576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com