- 论坛徽章:
- 0
|
程序实现的功能是在管道fifo1中读数据,然后写入管道fifo2中;可是运行结果是只读了一次,然后不停的写,请问下是什么情况?
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int fds[2];
char buf[7];
int i,rc,maxfd;
fd_set inset1,inset2;
struct timeval tv;
/**********creat fifo**********/
if(((mkfifo("/tmp/fifo1",O_CREAT|O_EXCL|O_RDONLY))<0) && (errno != EEXIST))
printf("cannot creat fifoserver.\n");
if(((mkfifo("/tmp/fifo2",O_CREAT|O_EXCL))<0) && (errno != EEXIST))
printf("cannot creat fifoserver2.\n");
/************open fifo****************/
if((fds[0] = open("/tmp/fifo1",O_RDWR|O_NONBLOCK,0))<0)
perror("open fifo1");
if((fds[1] = open("/tmp/fifo2",O_RDWR|O_NONBLOCK,0))<0)
perror("open fifo2");
if((rc = write(fds[0],"hello!\n",7)))
printf("rc=%d\n",rc);
lseek(fds[0],0,SEEK_SET);
maxfd = fds[0]>fds[1] ? fds[0]:fds[1];
FD_ZERO(&inset1);
FD_SET(fds[0],&inset1);
FD_ZERO(&inset2);
FD_SET(fds[1],&inset2);
while(FD_ISSET(fds[0],&inset1) || FD_ISSET(fds[1],&inset2))
{
if((i=select(maxfd+1,&inset1,&inset2,NULL,NULL)) < 0)
{
perror("select");
}
else
{
printf("%d %d \n",fds[0],fds[1]);
printf("%d\n",i);
if (FD_ISSET(fds[0],&inset1))
{
printf("read rc=%d \n",FD_ISSET(fds[0],&inset1));
rc = read(fds[0],buf,7);
if(rc>0)
{
buf[rc]='\0';
printf("read: %s\n",buf);
}
else
perror("read");
}
if (FD_ISSET(fds[1],&inset2))
{
rc = write(fds[1],buf,7);
if(rc>0)
{
buf[rc]='\0';
printf("write: %s\n",buf);
sleep(2);
}
else
perror("write");
}
}
}
close(fds[0]);
close(fds[1]);
exit(0);
}
|
|