【发布时间】:2014-09-17 14:04:01
【问题描述】:
美好的一天!我有一个通过posix_spawn 函数创建的进程。我怎样才能得到他的退出代码?
我知道waitpid() 函数,但它返回子进程的状态。此外,如果进程仍然有效并且我将调用 waitpid() 函数,那么我将收到正确的信息,说明该进程尚未关闭。
这是我当前的代码:
int GetExitCode()
{
int status;
int rtn = waitpid(pid, &status, WNOHANG);
if (rtn > 0) // still live
{
return -1;
}
rtn = waitpid(pid, &status, WUNTRACED);
if (rtn != -1 || errno != ECHILD)
{
// Here I got rtn = -1 and errno #10
}
if (WIFEXITED(status))
{
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
但是如何检查非子进程的退出状态?谢谢!
已更新。我的新代码:
int GetExitCode()
{
int status = 0;
int rtn = kill(pid, 0);
if (rtn == -1 && errno == ESRCH)
{
return 0;
}
rtn = waitpid(pid, &status, WNOHANG | WUNTRACED | WCONTINUED);
if (rtn == 0) // still live
{
return 0;
}
std::cout << "Probably success. Errno: " << errno << ". StrError: " << strerror(errno) << std::endl;
if (WIFEXITED(status))
{
return 1;
}
return 0;
}
【问题讨论】:
-
posix_spawn函数与fork一样返回一个进程ID,这意味着您可以使用普通的wait系列函数。事实上,创建的进程是你的进程的一个子进程,就像你用fork创建一个进程一样。 -
@JoachimPileborg:我认为这应该是一个答案。这个问题的全部基础似乎是OP对“子进程”的含义感到困惑。
-
如果是这样,那么为什么 waitpid 返回错误代码 10 "No child processes" ?我希望看到终止状态......我在哪里犯了错误?谢谢
-
您能否在您的问题中添加一些代码以显示您在做什么? Minimal, Complete, and Verifiable example 将是完美的。
-
抱歉,第一篇文章已更新