人工智能学习

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
-------------
*/
————————————————

这篇关于waitpid WNOHANG的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!