简体   繁体   中英

Error errno 11 Resource temporarily unavailable

I am using USB to Uart converter for transmission and reception for my data. Here is my code for transmission

void main()
{
int USB = open( "/dev/ttyUSB0", O_RDWR | O_NONBLOCK | O_NDELAY);        
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);

/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);

/* Setting other Port Stuff */
tty.c_cflag     &=  ~PARENB;            // Make 8n1
tty.c_cflag     &=  ~CSTOPB;
tty.c_cflag     &=  ~CSIZE;
tty.c_cflag     |=  CS8;

tty.c_cflag     &=  ~CRTSCTS;           // no flow control
tty.c_cc[VMIN]   =  1;                  // read doesn't block
tty.c_cc[VTIME]  =  5;                  // 0.5 seconds read timeout
tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines

/* Make raw */
cfmakeraw(&tty);

/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );

/*  WRITE */   
unsigned char cmd[] = "YES this program is writing \r";
int n_written = 0,spot = 0;
do {
n_written = write( USB, &cmd[spot], 1 );
spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);

The output of my code is same as expacted

YES this program is writing 

Now this is my code for reading from UART

/* READ   */
int n = 0,spot1 =0;
char buf = '\0';

/* Whole response*/
char response[1024];
memset(response, '\0', sizeof response);

do {
n = read( USB, &buf, 1 );
sprintf( &response[spot1], "%c", buf );
spot1 += n;
} while( buf != '\r' && n > 0);

if (n < 0) {
printf("Error reading %d %s",errno, strerror(errno));
}
else if (n==0) {
printf("read nothing");
}
else {
printf("Response %s",response);
}
}

This reading from Uart gives error from errno and it is error number 11 which says that Resource is temporary unavailable

I am getting this output

Error reading 11 Resource temporarily unavailable

I am using USB to UART converter. Hope someone could help. Thanks :)

You are getting the error code EAGAIN from your read call and this is causing you to exit your loop and print out the error. Of course EAGAIN means that this was a temporary problem (eg there wasn't anything to read at the time you tried to read it, perhaps you'd like to try later?).

You could restructure the read to be similar to:

n = read(USB, &buf, 1)
if (n == 0) {
    break;
} else if (n > 0) {
    response[spot1++] = buf;
} else if (n == EAGAIN || n == EWOULDBLOCK)
    continue;
} else { /*unrecoverable error */
    perror("Error reading");
    break;
}

You could improve your code by making buf be an array and reading more than one character at a time. Also notice that sprintf was unnecessary, you can just copy the character(s) in to the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM