parent 进程如何将 child 进程退出代码转换为状态代码?
How does parent process convert child process exit code to status code?
当我运行下面的代码(headers和主条目省略)
void fork11()
{
pid_t pid[N];
int i;
int child_status;
for (i = 0; i < N; i++)
if ((pid[i] = fork()) == 0)
exit(100+i); /* Child */
for (i = N-1; i >= 0; i--) {
pid_t wpid = waitpid(pid[i], &child_status, 0);
if (WIFEXITED(child_status)) {
printf("Child %d terminated with exit status %d\n", wpid, WEXITSTATUS(child_status));
printf("child_status: %d\n", child_status);
} else {
printf("Child %d terminate abnormally\n", wpid);
}
}
}
结果是
Child 5126 terminated with exit status 104
child_status: 26624
Child 5125 terminated with exit status 103
child_status: 26368
Child 5124 terminated with exit status 102
child_status: 26112
Child 5123 terminated with exit status 101
child_status: 25856
Child 5122 terminated with exit status 100
child_status: 25600
经过一番挖掘,我发现 WEXITSTATUS
是一个简单的宏
#define WEXITSTATUS(x) ((_W_INT(x) >> 8) & 0x000000ff)
以child进程5126为例,waitpid
将104
转换为26624=0x6800
,WEXITSTATUS
将26624
转换回104=0x68
,我试图查找 waitpid
的源代码,但最终得到了一些内核函数 which I can't understand... 谁能解释一下 waitpid
如何转换退出代码?上面的例子看起来很简单,但我认为它远不止于此,谢谢!
当进程退出时,传递给 exit()
函数的 return 值用作传递给等待等待的任何进程的实际 int
(4 字节)的参数它。除了这个状态码的8位之外,更多的信息正在被传递。
例如,在实际(最终)退出代码(整个 4 个字节)中,指定进程是否已发出信号。
所见here 关于WEXITSTATUS
:
This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3)
...
这意味着进程无法使用需要超过 8 位的代码退出。
当我运行下面的代码(headers和主条目省略)
void fork11()
{
pid_t pid[N];
int i;
int child_status;
for (i = 0; i < N; i++)
if ((pid[i] = fork()) == 0)
exit(100+i); /* Child */
for (i = N-1; i >= 0; i--) {
pid_t wpid = waitpid(pid[i], &child_status, 0);
if (WIFEXITED(child_status)) {
printf("Child %d terminated with exit status %d\n", wpid, WEXITSTATUS(child_status));
printf("child_status: %d\n", child_status);
} else {
printf("Child %d terminate abnormally\n", wpid);
}
}
}
结果是
Child 5126 terminated with exit status 104
child_status: 26624
Child 5125 terminated with exit status 103
child_status: 26368
Child 5124 terminated with exit status 102
child_status: 26112
Child 5123 terminated with exit status 101
child_status: 25856
Child 5122 terminated with exit status 100
child_status: 25600
经过一番挖掘,我发现 WEXITSTATUS
是一个简单的宏
#define WEXITSTATUS(x) ((_W_INT(x) >> 8) & 0x000000ff)
以child进程5126为例,waitpid
将104
转换为26624=0x6800
,WEXITSTATUS
将26624
转换回104=0x68
,我试图查找 waitpid
的源代码,但最终得到了一些内核函数 which I can't understand... 谁能解释一下 waitpid
如何转换退出代码?上面的例子看起来很简单,但我认为它远不止于此,谢谢!
当进程退出时,传递给 exit()
函数的 return 值用作传递给等待等待的任何进程的实际 int
(4 字节)的参数它。除了这个状态码的8位之外,更多的信息正在被传递。
例如,在实际(最终)退出代码(整个 4 个字节)中,指定进程是否已发出信号。
所见here 关于WEXITSTATUS
:
This consists of the least significant 8 bits of the status argument that the child specified in a call to
exit(3)
...
这意味着进程无法使用需要超过 8 位的代码退出。