C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > Linux C 获取进程的退出值

Linux C 获取进程退出值的实现代码

作者:

本篇文章是对在Linux下使用c语言获取进程退出值的方法进行了详细的分析介绍,需要的朋友参考下
如以下代码所示:
复制代码 代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char *argv[])
{
 pid_t pid;
 int stat;
 int exit_code;

 pid = fork();
 if(pid == 0)
 {
  sleep(3);
  exit(5);
 }
 else if( pid < 0 )
 {
  fprintf(stderr, "fork failed: %s", strerror(errno));
  return -1;
 }

 wait(&stat); // 等待一个子进程结束
 if(WIFEXITED(stat)) // 如果子进程通过 return, exit, _exit 正常结束, WIFEXITED() 返回 true
 {
  exit_code = WEXITSTATUS(stat);
  printf("child's exit_code: %d\n", exit_code);
 }

 return 0;
}

参考:  "man 2 wait"
您可能感兴趣的文章:
阅读全文