Maybe someone can answer this for me, I am confused. Why does the following code print ‘read(): Resource temporarily unavailable’ 80% of the time? That is the EAGAIN code, which is the same as WOULD BLOCK which means there is no data waiting to be read, but select is returning 1 saying there is data:
#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;
}
Related posts:
#1 by Fede on December 11, 2008 - 5:53 pm
Quote
You should reinitialize rfds after every select call.
There is data in fd only if FD_ISSET(fd, &rfds)
#2 by admin on December 11, 2008 - 6:06 pm
Quote
Changing it to:
do { FD_ZERO( &rfds ); FD_SET( fd, &rfds ); ret = select( fd + 1, &rfds, NULL, NULL, &sleep ); } while ((ret < 0 && (errno == EINTR)) || !FD_ISSET(fd, &rfds)); printf("ret was: %d\n", ret); if(FD_ISSET(fd, &rfds)) { printf("fd is set\n"); } else { printf("fd is not set\n"); }Is giving me:
ret was: 1
fd is set
read(): : Resource temporarily unavailable
#3 by Tim Kosse on December 11, 2008 - 6:13 pm
Quote
From ‘man select’:
Under Linux, select() may report a socket file descriptor as “ready for reading”, while nevertheless a subsequent
read blocks. This could for example happen when data has arrived but upon examination has wrong checksum and is
discarded. There may be other circumstances in which a file descriptor is spuriously reported as ready. Thus it
may be safer to use O_NONBLOCK on sockets that should not block.
#4 by Mike on December 12, 2008 - 5:05 am
Quote
What’s errno if it’s not EINTR *and* ret is less than 0? You don’t test that.