Php C、 exit和pcntl_wait函数产生256的倍数,为什么?
我正在编写一个测试,看看是否能够可靠地确定退出代码的整数值 使用Php C、 exit和pcntl_wait函数产生256的倍数,为什么?,php,c,exit,ubuntu-14.04,exit-code,Php,C,Exit,Ubuntu 14.04,Exit Code,我正在编写一个测试,看看是否能够可靠地确定退出代码的整数值 使用等待 问题 1.为什么退出代码乘以256? 2.是exit()、wait()、操作系统还是其他执行乘法的东西 复制问题的代码 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> // implementation is
等待
问题
1.为什么退出代码乘以256?2.是
exit()
、wait()
、操作系统还是其他执行乘法的东西
复制问题的代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
// implementation is correct but irrelevant to the question
int compareInt(const void* a, const void* b);
int main(void) {
pid_t pids[6];
int i;
for (i = 0; i < 6; i++) {
pid_t pid = fork();
pids[i] = pid;
if (pid == 0) {
exit(i);
}
}
int codes[6];
do {
i--;
wait(&codes[i]);
} while (i > 0);
const size_t num_elem = 6;
qsort(codes, num_elem, sizeof(int), compareInt);
for (i = 0; i < 5; i++) {
printf("%d, ", codes[i]);
}
printf("%d\n", codes[5]);
return 0;
}
输出:0、256、512、768、1024、1280
如果有区别的话,我运行的是Ubuntu 14.04,而
man wait
说我有wait(2)
wait()的返回值对几条信息进行了编码。定义了一些宏来分离结果并获得所需的细节。e、 g.WEXITSTATUS(result\u of_wait)
您看到这些结果的原因是因为wait()
返回的值经过编码,包含进程如何停止以及为什么停止以及实际退出状态等信息;这就是为什么提供方便宏来检查返回值的某些部分
WEXITSTATUS(status)
的定义可以在sys/wait.h
中找到,可能如下所示:
#define WEXITSTATUS(status) (((status) & 0xff00) >> 8)
或者这个:
#define WEXITSTATUS(status) (((status) >> 8) & 0x000000ff)
你看到乘法是因为:
exit(1) -> 0x0100 (256)
exit(2) -> 0x0200 (512)
在PHP中,您可以使用它来完成同样的事情;如果进程因信号而终止,则没有退出状态,您需要使用来确定用于终止它的信号。基本上是关于进程如何结束的信息-正常或不正常。阅读手册页上的完整列表。嗨,杰克,我不能马上找到你的答案(尽管它可能是正确的)。早上我会仔细看一看,如果你把资源链接到你找到宏定义的地方,会有帮助的。嗨,杰克,谢谢你的回答。这对我来说已经完全不神秘了。
exit(1) -> 0x0100 (256)
exit(2) -> 0x0200 (512)