【问题标题】:Error errno 11 Resource temporarily unavailable错误 errno 11 资源暂时不可用
【发布时间】:2015-10-14 07:09:48
【问题描述】:

我正在使用 USB 转 Uart 转换器来传输和接收我的数据。 这是我的传输代码

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);

我的代码输出和expacted一样

YES this program is writing 

现在这是我从 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);
}
}

从 Uart 读取的数据显示来自 errno 的错误,错误号 11 表示资源暂时不可用

我得到这个输出

Error reading 11 Resource temporarily unavailable

我正在使用 USB 到 UART 转换器。希望有人能帮忙。谢谢:)

【问题讨论】:

    标签: c usbserial


    【解决方案1】:

    您从read 调用中收到错误代码EAGAIN,这导致您退出循环并打印出错误。当然EAGAIN 表示这是一个暂时的问题(例如,当您尝试阅读它时没有任何可阅读的内容,也许您想稍后再试?)。

    您可以将读取重组为类似于:

    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;
    }
    

    您可以通过将buf 设为一个数组并一次读取多个字符来改进您的代码。另请注意,sprintf 是不必要的,您只需将字符复制到数组中即可。

    【讨论】:

    • AKA '我将它设置为非阻塞,当它没有阻塞时我很惊讶':)
    • 显示错误:continue 语句不在循环内
    • if (n==0) { break; } else if (n == EAGAIN || n == EWOULDBLOCK){ 继续; } else if (n>0) { printf("Response %s",response); } else { printf("读取 %d %s 时出错",errno, strerror(errno)); }
    • 不。我应该删除它吗??
    • @AbhishekParikh 不,保持循环... Dave 的代码替换循环内部。
    猜你喜欢
    • 2012-11-13
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多