3
爲什麼下面的代碼打印'read():資源暫時不可用'80%的時間?這是EAGAIN代碼,這是一樣的會阻止,這意味着沒有數據等待讀取,但選擇將返回1說有數據(在Linux中進行測試):爲什麼下面打印出「資源暫時不可用」?
#include <time.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/errno.h>
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;
}
其實我檢查了那個,ret總是= 1。其他人告訴我發生了什麼是select是返回有數據,但是讀取被阻塞,因爲校驗和或一些數據錯誤發生 – user10060 2008-12-11 22:56:56