linux内核分叉子返回状态

时间:2011-10-18 22:09:20

标签: c linux shell unix kernel

所以这就是我的困境:为什么当我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);
}

2 个答案:

答案 0 :(得分:6)

阅读wait(3)上的文档。返回的值是一个32位整数,包含退出状态(如果进程正常退出),以及许多标志位。要确定进程是否正常退出,请使用WIFEXITED()宏。如果返回true,则使用WEXITSTATUS()宏获取实际退出状态:

int status;
if(wait(&status) > 0)
{
    // Did the process exit normally?
    if(WIFEXITED(status))
    {
        // This is the value you really want
        int actual_status = WEXITSTATUS(status);
        ...
    }
}

答案 1 :(得分:3)

因为status不仅拥有子bu的返回码,而且还包含另一个信息 如果您想知道退出值,则必须使用WEXITSTATUS

来自等候手册的

  

WEXITSTATUS(状态)   返回子项的退出状态。这包括                 孩子的状态参数的最低8位                 在调用exit(3)或_exit(2)或作为参数时指定                 对于main()中的return语句。这个宏应该只是                 如果WIFEXITED返回true,则使用。

这意味着status整数包含另一个信息并提取此信息,您应该使用sys/wait.h中定义的宏