//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);
}