其他分享
首页 > 其他分享> > waitpid WNOHANG

waitpid WNOHANG

作者:互联网

waitpid WNOHANG

原文链接:https://blog.csdn.net/weixin_37787043/article/details/78714621

 

#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
//waitpid WNOHANG
int main(void)
{
  printf("main process pid = %d\n",getpid());
  int status;
  pid_t pid;
  pid = fork();//创建子进程
  if(pid < 0)
  {
    perror("fork error");
    exit(1);//结束进程
  }

  if(pid == 0)
  {
    printf("子进程pid = %d\n",getpid());
    sleep(3);
    printf("********\n");
    exit(2);
  }

  if(pid > 0)
  {
    printf("父进程pid = %d\n",getpid());

    //waitpid(pid,&status,0);//等同wait(&status);
    //WNOHANG,waitpid()不阻塞而且立即返回,返回值为0
    while(waitpid(pid,&status,WNOHANG) == 0)
    {
      printf("-----子进程运行中-----\n");
      sleep(1);
    }

    //判断子进程结束状态
    if(WIFEXITED(status))//进程正常结束
    {
      printf("normal exit status = %d\n",WIFEXITED(status));
    }

    if(WIFSIGNALED(status))//进程异常终止
    {
      printf("recv signal exit\n");
    }
    printf("-------------\n");
    exit(1);
  }

  return 0;
}
/*
$ ./a.out
main process pid = 24977
父进程pid = 24977
-----子进程运行中-----
子进程pid = 24978
-----子进程运行中-----
-----子进程运行中-----
********
-----子进程运行中-----
normal exit status = 1
-------------
*/
————————————————

标签:status,pid,WNOHANG,-----,printf,进程,exit,waitpid
来源: https://www.cnblogs.com/cqx6388/p/14892203.html