【发布时间】:2014-11-24 23:38:54
【问题描述】:
我正在编写一个测试,看看我是否可以可靠地确定退出代码的整数值
与wait。
问题
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
事实证明我应该使用wifexited(), wifstopped(), wifsignaled(), wexitstatus(), wtermsig(), or wstopsig() 来确定退出状态。
此外,相同的行为在 PHP 中是可重现的(我第一次遇到它的地方)
$pids = [];
foreach (range(0, 5) as $i) {
$pids[] = $pid = pcntl_fork();
if ($pid === 0) {
exit($i);
}
}
$exit_codes = [];
do {
pcntl_wait($exit_codes[]);
array_pop($pids);
} while (count($pids) > 0);
sort($exit_codes);
echo implode(', ', $exit_codes) . "\n";
输出: 0, 256, 512, 768, 1024, 1280
如果有什么不同,我正在运行 Ubuntu 14.04,man wait 说我有 WAIT(2)
【问题讨论】:
标签: php c exit ubuntu-14.04 exit-code