使用有名管道双方进行聊天通信

client_fifo:

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

int main(void)
{
	 printf("开始微信聊天\n");
	//创建一个进程
	 pid_t  pid = fork();
	if(pid == 0)   //子进程
	{	 
		int  fd=open("/home/gec/pipe2",O_RDWR);
		 if(fd < 0)
		{
			perror("fd error:");
			return 0;
		}	
		//读取对方发送过来的数据
		while(1)
		{
			char buf[1024]={0};
			//读取对方消息
			read(fd,buf,1024);
			printf("小米: %s\n",buf);
		}
	}
	//打开管道文件   
       int  fd=open("/home/gec/pipe",O_RDWR);
		  if(fd < 0)
		  {
			perror("");
			return 0;
		  }
	  //不断往管道写入数据
	while(1)
	{
		char buf[1024]={0};
		scanf("%s",buf);
		//写入数据
		write(fd,buf,strlen(buf));
	}
	//关闭管道文件 
	close(fd);
	return 0;
}

server_fifo:

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

int main(void)
{
	 printf("开始微信聊天\n");
	 pid_t pid = fork();
     if(pid == 0)
	 {
		int  fd=open("/home/gec/pipe2",O_RDWR);
		if(fd < 0)
		{
			perror("");
			return 0;
		}
		 //不断往管道中写入数据
		while(1)
		{
			char buf[1024]={0};
		    scanf("%s",buf);
		    //写入数据
			write(fd,buf,strlen(buf));	
		}		
	 }
	//1.打开管道文件   
    int  fd=open("/home/gec/pipe",O_RDWR);
	if(fd < 0)
	{
		perror("");
		return 0;
	}  
	//不断读取管道中的数据
	while(1)
	{
		char buf[1024]={0};
		read(fd,buf,1024);
		printf("华为: %s\n",buf);
	}
	//关闭管道文件 
	close(fd);
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值