原程序:
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int fds[2];
char buf[100];
int i,rc,maxfd;
fd_set inset1,inset2;
struct timeval tv;
if((fds[0] = open("hello1",O_RDWR | O_CREAT,0666))<0)
perror("open hello1");
if((fds[1] = open("hello2",O_RDWR | O_CREAT,0666))<0)
perror("open hello2");
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);
tv.tv_sec=2;
tv.tv_usec=0;
while(FD_ISSET(fds[0],&inset1) || FD_ISSET(fds[1],&inset2))
{
if(select(maxfd+1,&inset1,&inset2,NULL,&tv)<0)
perror("select");
else
{
if(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("rc=%d,write:%s\n",rc,buf);
}
else
perror("write");
sleep(10);
}
}
}
exit(0);
}
运行结果:
[root@localhost exp]# ./select
rc=7
read: hello!
rc=7,write:hello!
read: Success
rc=7,write:hello!
read: Illegal seek
rc=7,write:hello!
read: Illegal seek
rc=7,write:hello!
read: Illegal seek
rc=7,write:hello!
原程序意图:将文件hello1里的内容读出,并将此内容每隔10秒写到hello2里面
问题:1):为什么会出现read: Success??
2):为什么会出现read: Illegal seek???
这个是你的程序. 运行了perror("read");
因为你的hello1文件已经读完了.读到文件的最后了,你还让他读,他就报错了.
程序建议:perror("read")写成perror("read error");这样一眼就看出来了.
while(FD_ISSET(fds[0],&inset1) || FD_ISSET(fds[1],&inset2))
你的这里的判断是没有意思的.因为你的fds[0],fds[1]都是读写打开的,他们始终都是可以读写的.
select(maxfd+1,&inset1,&inset2,NULL,&tv),这里的tv时间也是永远用不到.