Linux内核分叉子状态返回
所以这是我的困境:为什么当我 fork();
一个进程的子进程并且它结束时,返回的子进程的 &status
向左移动 8少量?
例如,假设我在分叉子进程的末尾有 exit(4);
,我的状态在 wait(&status);
父进程的值获取到 0x400
。
所以这是一些代码来说明我的意思
#include <stdio.h>
main() {
int n, status, cpid;
printf("Parent pid = %d\n", getpid());
n = fork();
if (n != 0) {
// parent code
printf ("I'm the parent with PID %d \t fork returned %d \t my parent is %d\n", getpid(), n, getppid());
status = 0;
sleep(5); // verify status of child
cpid = wait(&status);
// so when i printf the hex value of status it gets shifted
printf("I received from my child %d this information %x\n", cpid, status);
} else {
// child code
printf ("I'm the child with PID %d \t fork returned %d \t my parent is %d\n", getpid(), n, getppid());
sleep(20);
printf("Child complete\n");
status=12345;
// the line that returns the shifted value
exit(4);
}
printf("Parent complete\n");
exit(15);
}
So here's my dilemma: Why when I fork();
a child of a process and it ends, the returned &status
of the child is shifted to the left by 8 bit?
For example let's say i have exit(4);
at the end of the forked child , my status in the wait(&status);
of the father process gets me 0x400
.
so here is some code that illustrates what I mean
#include <stdio.h>
main() {
int n, status, cpid;
printf("Parent pid = %d\n", getpid());
n = fork();
if (n != 0) {
// parent code
printf ("I'm the parent with PID %d \t fork returned %d \t my parent is %d\n", getpid(), n, getppid());
status = 0;
sleep(5); // verify status of child
cpid = wait(&status);
// so when i printf the hex value of status it gets shifted
printf("I received from my child %d this information %x\n", cpid, status);
} else {
// child code
printf ("I'm the child with PID %d \t fork returned %d \t my parent is %d\n", getpid(), n, getppid());
sleep(20);
printf("Child complete\n");
status=12345;
// the line that returns the shifted value
exit(4);
}
printf("Parent complete\n");
exit(15);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
阅读有关
wait(3)
的文档。返回的值是一个 32 位整数,包含退出状态(如果进程正常退出)以及一些标志位。要确定进程是否正常退出,请使用WIFEXITED()
宏。如果返回 true,则使用WEXITSTATUS()
宏获取实际退出状态:Read the documentation on
wait(3)
. The value returned is a 32-bit integer containing the exit status (if the process exited normally), as well as a number of flag bits. To determine if the process exited normally, use theWIFEXITED()
macro. If that returns true, then use theWEXITSTATUS()
macro to get the actual exit status:因为
status
不仅保存子进程的返回代码,还保存其他信息。如果你想知道退出值,你必须使用
wait 手册中的
WEXITSTATUS
宏:这意味着
status
整数保存着另一个信息,要提取此信息,您应该使用sys/wait.h
中定义的宏Because
status
hold not only the return code of the child bu it holds another information.if you want to know the exit value you have to use the
WEXITSTATUS
macrofrom wait manual:
that's mean that the
status
integer holds another information and to extract this information you should use the macros which defined insys/wait.h