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

标签 c fork waitpid

只需查询有关使用 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;
  }

我希望状态打印 1,但它打印 256(添加了一个字节 0)

谁能解释一下这是为什么?我是 C 的新手,所以请原谅这个问题对专家来说可能很愚蠢。

最佳答案

来自 man waitpid :

If wstatus is not NULL, wait() and waitpid() store status information in the int to which it points. 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()!):

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().

所以你应该:

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

关于c - 关于使用 fork() 创建的子进程的退出状态值的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56336025/

相关文章:

c - 使用 scanf 时程序立即终止并出现段错误

c - 库中的 SIGCHLD 和 fork + waitpid()

linux - waitpid - 第一个参数 pid=-1 和 pid=0 之间的区别

c - 如何从子进程更新共享数据?

UNIX 进程 : fork() and wait()

linux - 如何使用 `waitpid()` 处理程序在主程序中调用 `SIGCHLD` 设置的插件中安全地使用 `wait()`

c - printf 的最大数字信息密度

c - fprintf 的错误

c - Linux环境下malloc杀死子进程

c - 等待子执行