我有这个代码:
int status;
t = wait(&status);
当子进程工作时,status的值为0,嗯。
但是为什么不行就返回256呢?为什么在出现错误时更改子进程中退出的参数值不会改变任何内容(例如 exit(2) 而不是 exit(1))?
编辑:我在 linux 上,我用 GCC 编译。
最佳答案
给定这样的代码...
int main(int argc, char **argv) {
pid_t pid;
int res;
pid = fork();
if (pid == 0) {
printf("child\n");
exit(1);
}
pid = wait(&res);
printf("raw res=%d\n", res);
return 0;
}
...res
的值将为 256
。这是因为 wait
的返回值编码了进程的退出状态以及进程退出的原因。通常,您不应尝试直接解释 wait
的非零返回值;您应该使用 WIF...
宏。例如查看一个进程是否正常退出:
WIFEXITED(status)
True if the process terminated normally by a call to _exit(2) or
exit(3).
然后获取退出状态:
WEXITSTATUS(status)
If WIFEXITED(status) is true, evaluates to the low-order 8 bits
of the argument passed to _exit(2) or exit(3) by the child.
例如:
int main(int argc, char **argv) {
pid_t pid;
int res;
pid = fork();
if (pid == 0) {
printf("child\n");
exit(1);
}
pid = wait(&res);
printf("raw res=%d\n", res);
if (WIFEXITED(res))
printf("exit status = %d\n", WEXITSTATUS(res));
return 0;
}
您可以在 wait(2)
手册页中阅读更多详细信息。
关于c - 我用了wait(&status),status的值为256,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24130990/