获取使用fork()创建的子进程的返回代码



我正在尝试获取由fork((创建的子进程的返回代码。我正在使用wait((函数来获取返回代码。一切正常,但wait((给出的返回值是实际返回值的256倍。有人能解释为什么吗。

代码:

#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
constexpr int PROCESS_COUNT = 7;
int main() {
pid_t pid;

for (int i = 0; i < PROCESS_COUNT; i++) {
pid = fork();
if (pid > 0) {
int returnCode;
int pid;
pid = wait(&returnCode);
std::cout << "n Process: " << pid << "; i: " << i
<< "; Return Code: " << returnCode << std::endl;
}
else {
return i;
}
}
return EXIT_SUCCESS;
}

输出:


Process: 7910; i: 0; Return Code: 0
Process: 7911; i: 1; Return Code: 256
Process: 7912; i: 2; Return Code: 512
Process: 7913; i: 3; Return Code: 768
Process: 7914; i: 4; Return Code: 1024
Process: 7915; i: 5; Return Code: 1280
Process: 7916; i: 6; Return Code: 1536

请阅读wait手册页面。wait给出的值不仅包含子进程退出代码,还包含其他标志和值。

要获得退出状态,首先需要确保子进程确实以正常方式退出。这是通过WIFEXITED宏完成的。

然后使用WEXITSTATUS宏获取实际状态。

类似这样的东西:

pid_t pid = wait(&returnCode);
if (pid >= 0 && WIFEXITED(returnCode))
{
std::cout << "Child process " << pid << " exited normally with return code " << WEXITSTATUS(returnCode) << 'n';
}

注意,我添加了";正确的";类型实际上是由wait返回的,我还检查了它以确保wait没有失败。

最新更新