linux内核分叉子返回状态

Luc*_*che 2 c unix linux shell 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);
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*eld 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);
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)