简体   繁体   English

有关使用fork()创建的子进程的退出状态的值的查询

[英]A Query regarding the value of Exit Status of Child Process Created with fork()

Just have a query about Status of Child processes created with fork() 只是有一个关于使用fork()创建的子进程状态的查询

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main (){
    int pid;
    int status;

    printf("Parent: %d\n", getpid());

    pid = fork();
    if (pid == 0){
        printf("Child %d\n", getpid());
        sleep(4);
        exit(1);
       }

  waitpid(pid, &status, 0);

  printf("The status of child is %u\n",status);


  printf("Parent: %d\n", getpid());

  return 0;
  }

I expect the status to print 1 , but it prints 256(a byte of 0's is added ) 我希望状态打印为1,但它打印256(添加0的字节)

Can someone explain why is this? 有人可以解释为什么吗? I am a newbie to C , so please excuse as this question may appear silly to the experts. 我是C的新手,因此请原谅,因为此问题对专家们可能看起来很愚蠢。

From man waitpid : man waitpid

If wstatus is not NULL, wait() and waitpid() store status information in the int to which it points. 如果wstatus不为NULL,则wait()和waitpid()将状态信息存储在它指向的int中。 This integer can be inspected with the following macros (which take the integer itself as an argument, not a pointer to it, as is done in wait() and waitpid()!): 可以使用以下宏检查该整数(这些宏将整数本身作为参数,而不是指向它的指针,就像在wait()和waitpid()中一样!):

WEXITSTATUS(stat_val) WEXITSTATUS(stat_val)

If the value of WIFEXITED(stat_val) is non-zero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to _exit() or exit(), or the value the child process returned from main(). 如果WIFEXITED(stat_val)的值不为零,则此宏求值为子进程传递给_exit()或exit()的状态参数的低8位,或者该子进程从main返回的值()。

So you should: 因此,您应该:

printf("The status of child is %u\n", WEXITSTATUS(status));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM