19,612
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd;
if((fd=open("./c.txt",O_CREAT|O_RDWR|S_IRUSR|S_IWUSR))==-1)
{
perror("open");
return 1;
}
const char *str="Hello World";
if(write(fd,str,strlen(str))!=strlen(str))
{
perror("write");
return 2;
}
if(lseek(fd,0,SEEK_SET)==-1)
{
perror("lseek");
return 3;
}
fd_set rSet,rec;
FD_ZERO(&rSet);
FD_SET(fd,&rSet);
rec=rSet;
int nfd;
while(true)
{
if( (nfd=select(fd+1,&rSet,NULL,NULL,NULL))>0 )
{
if(FD_ISSET(fd,&rSet))
{
char buffer[100];
int n;
if( (n=read(fd,buffer,100))>0 )
{
buffer[n]='\0';
printf("%s\n",buffer);
}
else if(n==0)
{
printf("EOF\n");
break;
}
else
{
perror("read");
return 4;
}
}
}
else if(nfd==0)
{
printf("out of time\n");
}
else
{
perror("select");
return 5;
}
rSet=rec;
}
return 0;
}
linux-t4lu:/home/owenliang/csdn/cAndCpp # ./main
Hello World
EOF
select() and pselect() return the number of file descriptors contained in the three returned descriptor sets (that is, the total num‐
ber of bits that are set in readfds, writefds, exceptfds) which may be zero if the timeout expires before anything interesting happens.
ssize_t read(int fd, void *buf, size_t count);
On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number.