打印

关于select()函数的问题

[复制链接]
1538|0
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
lgw150|  楼主 | 2008-12-2 15:43 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
2008.11.30
原程序:
#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???

相关帖子

发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

3

主题

3

帖子

0

粉丝