命名管道(FIFO)聊天程序

//A.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <error.h>
int main()
{
 int i,rfd,wfd,len=0;
 char str[32];
 int flag,stdinflag;
 fd_set read_fd;
 struct timeval net_timer;
 mkfifo("fifo1",S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH);           //管道只能实现单向通信,需创建两个管道
 mkfifo("fifo2",S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH);
 wfd=open("fifo1",O_WRONLY);
 rfd=open("fifo2",O_RDONLY);
 if(rfd<=0||wfd<=0)
  return 0;
 printf("A\n");
 while(1)
 {
  FD_ZERO(&read_fd);
  FD_SET(rfd,&read_fd);
  FD_SET(fileno(stdin),&read_fd);
  net_timer.tv_sec=5;
  net_timer.tv_usec=0;
  memset(str,0,sizeof(str));
  if(i=select(rfd+1,&read_fd,NULL,NULL,&net_timer)==0)   //利用select完成非阻塞监听
   continue;
  else if(i<0)
   exit(1);
  if(FD_ISSET(rfd,&read_fd))
  {
   if(read(rfd,str,sizeof(str))>0)
    printf("B:%s",str);
  }
  if(FD_ISSET(fileno(stdin),&read_fd))
  {
   fgets(str,sizeof(str),stdin);
   len=write(wfd,str,sizeof(str));
  }
 }
 close(rfd);
 close(wfd);
}

 

//B.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <error.h>
int main()
{
 int i,rfd,wfd,len=0;
 char str[32];
 int flag,stdinflag;
 fd_set read_fd;
 struct timeval net_timer;
 mkfifo("fifo1",S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH);
 mkfifo("fifo2",S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH);
 rfd=open("fifo1",O_RDONLY);
 wfd=open("fifo2",O_WRONLY);
 if(rfd<=0||wfd<=0)
  return 0;
 printf("B\n");
 while(1)
 {
  FD_ZERO(&read_fd);
  FD_SET(rfd,&read_fd);
  FD_SET(fileno(stdin),&read_fd);
  net_timer.tv_sec=5;
  net_timer.tv_usec=0;
  memset(str,0,sizeof(str));
  if(i=select(rfd+1,&read_fd,NULL,NULL,&net_timer)==0)
   continue;
  else if(i<0)
   exit(1);
  if(FD_ISSET(rfd,&read_fd))
  {
   if(read(rfd,str,sizeof(str))>0)
    printf("A:%s",str);
  }
  if(FD_ISSET(fileno(stdin),&read_fd))
  {
   fgets(str,sizeof(str),stdin);
   len=write(wfd,str,sizeof(str));
  }
 }
 close(rfd);
 close(wfd);
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值