select()函数问题

原程序:#include<fcntl.h>#include<stdio.h>#include<unistd.h>#include<stdlib.h>#include<ti... 原程序:
#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???
展开
 我来答
FamDestiny
2008-12-03 · TA获得超过610个赞
知道小有建树答主
回答量:244
采纳率:100%
帮助的人:120万
展开全部
原因在于每次读完以后文件读取指针发生偏移,这个再读就读没有数据了,而你并没有清零buf.指针也没有回位,所以出那个提示。改好了

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <string.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_ZERO(&inset2);
tv.tv_sec=2;
tv.tv_usec=0;
while(1)//你那个的逻辑感觉不太好
{
bzero(buf, 100);//清零buf
lseek(fds[0],0,SEEK_SET);//指针归位
FD_SET(fds[0],&inset1);//
FD_SET(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(1);
}
}

}
exit(0);
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式