23,217
社区成员




// Linux include
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <stdio.h>
#include <iostream>
int main()
{
int mdevFd = -1;
mdevFd = open("has_sd_card", O_RDONLY|O_NONBLOCK);
if (mdevFd < 0) {
std::cout << "Open file failed." << std::endl;
return -1;
}
std::cout << mdevFd << std::endl;
int ret;
char value;
fd_set rd;
struct timeval tv;
while (true) {
FD_ZERO(&rd);
FD_SET(mdevFd, &rd);
tv.tv_sec = 0;
tv.tv_usec = 1000000; /* timeout 1000 ms */
std::cout << "1" << std::endl;
ret = select(mdevFd + 1, &rd, NULL, NULL, &tv);
std::cout << "2" << std::endl;
if (ret > 0 && read(mdevFd, &value, sizeof(char)) > 0) {
std::cout << "File updated, value = " << value << std::endl;
}
std::cout << "once" << std::endl;
}
close(mdevFd);
return 0;
}
while (true) {
FD_ZERO(&rd);
FD_SET(mdevFd, &rd);
tv.tv_sec = 0;
tv.tv_usec = 1000000; /* timeout 1000 ms */
std::cout << "1" << std::endl;
ret = select(mdevFd + 1, &rd, NULL, NULL, &tv);
std::cout << "2" << std::endl;
if (ret > 0 && read(mdevFd, &value, sizeof(char)) > 0) {
std::cout << "File updated, value = " << value << std::endl;
}
std::cout << "once" << std::endl;
}
如果在一个描述符上碰到了文件尾端,则select会认为该描述符是可读。然后调用read,它返回0,这是UNIX系统指示到达文件尾端的方法。注:这不是异常。