一.进程间通信中无名管道通信时遇到的阻塞问题时的调试方案。

本文介绍了无名管道通信中遇到的阻塞问题及其测试。通过示例代码展示了如何创建无名管道,并在父子进程中实现数据传输。在父进程中,使用fcntl设置读取为非阻塞模式,不断读取并打印子进程发送的数据。同时,文章还包含了子进程结束后的回收逻辑,确保资源得到正确释放。
摘要由CSDN通过智能技术生成

1.无名管道通信

遇到的阻塞问题时的测试。
由于无名管道有默认的阻塞特性。

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>

int main(int argc,char **argv)
{ //管道文件,亲缘进程间通信,在内存中 fifo 半双工,
  
    int fd[2];//创建文件描述符fd[0]读 fd[1]写
    if(pipe(fd)<0)//无名管道的创建
    {
        perror("pipe error:");
        exit(1);
    }
   

    char buf[50]="who is me!"; 
   	int x;//创建进程
   	for(x=0;x<1;x++)
	{ 	
		pid_t pid=fork();
 		if(pid==0)
 		break;
	}
    if(x==0)
    {
        
      write(fd[1],buf,strlen(buf));
    }
    if(pid==1)
    { fcntl(fd[0],F_SETFL,O_NONBLOCK);//非阻塞
      //fcntl(fd[0],F_SETFL,0);//阻塞
        while(1)
        {//读取亲缘进程发送的消息
          memset(buf,0,sizeof(buf));
          read(fd[0],buf,sizeof(buf));
          printf("buf :%s\n",buf);
          sleep(1);
  
        }
     }

     pid_t ret;//回收子进程
     while((ret=waitpid(-1,&x,WNOHANG)!=-1)
     {
		if(ret==0)
		continue;
		if(WIFEXITED(x))
		{
			printf("回收状态 %d\n",WEXITSTATUS(x));
		}
		if(WIFSIGNALED(x))
		{
			pritnf("信号杀死 %d\n",WTERMSIG(x));
		}
	 }

    close(fd[0]);//关闭文件描述符
    close(fd[1]);
  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值