为什么以下代码打印'read():资源暂时不可用'80%的时间?这是EAGAIN代码,它与WOULD BLOCK相同,这意味着没有数据等待读取,但是select返回1表示有数据(在Linux中测试):
#include#include #include #include #include #include #include #include int main(int argc, char** argv) { int fd = open("/dev/lp0", O_RDWR | O_NONBLOCK); int ret = 0; int status = 0; char buffer[1024]; char teststr[] = "This is a test\n"; char XMIT_STATUS_OFFLINE[] = {0x10,0x04,0x02}; char XMIT_STATUS_ERROR[] = {0x10,0x04,0x03}; char XMIT_STATUS_ROLL[] = {0x10,0x04,0x04}; char XMIT_STATUS_SLIP[] = {0x10,0x04,0x05}; fd_set rfds; FD_ZERO( &rfds ); FD_SET( fd, &rfds ); struct timeval sleep; sleep.tv_sec = 5; sleep.tv_usec = 0; /* Offline status */ ret = write(fd, XMIT_STATUS_OFFLINE, sizeof(XMIT_STATUS_OFFLINE)); //printf("write() returned %d\n", ret); do { ret = select( fd + 1, &rfds, NULL, NULL, &sleep ); } while (ret < 0 && (errno == EINTR)); ret = read(fd, buffer, 1024); if(ret == -1) { perror("read(): "); } else { status = buffer[0]; if((status & 0x04) != 0) { printf("The cover is open.\n"); } else { printf("OFFLINE is good.\n"); } } close(fd); return 0; }
SoapBox.. 6
如果没有可用的数据,在经过5秒超时后,您的选择调用将返回0.您的代码将忽略此操作并尝试从设备读取.检查ret == 0,这将解决您的问题.
如果没有可用的数据,在经过5秒超时后,您的选择调用将返回0.您的代码将忽略此操作并尝试从设备读取.检查ret == 0,这将解决您的问题.