您的位置:首页 > 运维架构 > Linux

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

2018-10-12 13:58 561 查看
如以下代码所示:

#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"

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: