管道的破裂pipe_broken

发布于:2023-01-04 ⋅ 阅读:(327) ⋅ 点赞:(0)

判断进程终止异常函数

#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *wstatus);
参数:
    wstatus:进程结束时,状态信息的首地址返回值:
    成功返回子进程结束的pid号,失败返回-1;
    如果想得到进程结束的状态信息,可以用以下宏来的到:
    WIFEXITED(wstatus)--判断一个子进程是否正常退出,正常退出为真(1),非正常退出为假(非正数)
    WEXITSTATUS(wstatus)--返回子进程结束的返回值
    WIFSIGNALED(wstatus)--判断是否被信号终止
    WTERMSIG(wstatus)--打印进程信号的编号

/*===============================================
 *   文件名称:pipe_broken.c
 *   创 建 者:     
 *   创建日期:2022年08月29日
 *   描    述:
 ================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
    int pfd[2]={0};//管道两个端口
   int ret= pipe(pfd);//创建管道
   if(ret<0)
   {
     perror("pipe");
     exit(-1);
   }
    close(pfd[0]);//关闭读端

    pid_t pid=fork();//创建子进程
    if(pid<0)
    {
      perror("fork");
      exit(-1);
    }
    if(pid==0)
    {
        int ret;
        char buf[64]={0};
        fgets(buf,64,stdin);
        write(pfd[1],buf,strlen(buf));//在终端向管道写入
        sleep(2);
    }
    else
    {
        int status;//定义状态信息首地址
        wait (&status);
        printf("进程编号:%d\n是否正常退出%d\n是否被终止:%d\n",WTERMSIG(status),WIFEXITED(status),WIFSIGNALED(status));//结束进程
    }
  return 0;

}
结果测试:

 

本文含有隐藏内容,请 开通VIP 后查看