Linux - 串口读取返回EAGAIN

And*_*ira 10 c linux serial-port

我在从以下方式打开的串口读取一些数据时遇到了一些麻烦.我已经多次使用这个代码实例并且一切正常,但现在,由于某些原因我无法弄清楚,我完全无法从串口读取任何内容.

我能够写,并且所有都在另一端正确接收,但是从未收到回复(正确发送)(不,电缆都可以;))

我用来打开串口的代码如下:

fd = open("/dev/ttyUSB0", O_RDWR | O_NONBLOCK | O_NOCTTY);
if (fd == -1)
{
    Aviso("Unable to open port");
    return (fd);
}
else
{
    //Get the current options for the port...
    bzero(&options, sizeof(options)); /* clear struct for new port settings */
    tcgetattr(fd, &options);

    /*-- Set baud rate -------------------------------------------------------*/
    if (cfsetispeed(&options, SerialBaudInterp(BaudRate))==-1)
        perror("On cfsetispeed:");
    if (cfsetospeed(&options, SerialBaudInterp(BaudRate))==-1)
        perror("On cfsetospeed:");

    //Enable the receiver and set local mode...
    options.c_cflag |= (CLOCAL | CREAD);
    options.c_cflag &= ~PARENB; /* Parity disabled */
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;  /* Mask the character size bits */
    options.c_cflag |= SerialDataBitsInterp(8);           /* CS8 - Selects 8 data bits */
    options.c_cflag &= ~CRTSCTS;                            // disable hardware flow control
    options.c_iflag &= ~(IXON | IXOFF | IXANY);           // disable XON XOFF (for transmit and receive)
    options.c_cflag |= CRTSCTS;                         /* enable hardware flow control */

    options.c_cc[VMIN] = 0;     //min carachters to be read
    options.c_cc[VTIME] = 0;    //Time to wait for data (tenths of seconds)

    //Set the new options for the port...
    tcflush(fd, TCIFLUSH);
    if (tcsetattr(fd, TCSANOW, &options)==-1)
    {
        perror("On tcsetattr:");
    }

    PortOpen[ComPort] = fd;
}

return PortOpen[ComPort];
Run Code Online (Sandbox Code Playgroud)

初始化端口后,我通过简单的写命令写一些东西给它...

int nc = write(hCom, txchar, n);
Run Code Online (Sandbox Code Playgroud)

其中hCom是文件描述符(并且没关系),并且(正如我所说)这是有效的.但是......当我事后阅读时,我从errno得到一个"暂时不可用的资源"错误.

我测试了选择以查看文件描述符何时读取...但它总是超时!

我读了这样的数据:

ret = read(hCom, rxchar, n);
Run Code Online (Sandbox Code Playgroud)

我总是得到一个EAGAIN,我不知道为什么.

更新:

硬件工作正常!我可以看到串口上有入站数据,因为我已经制作了一条调试电缆来读取在另一个终端上发生的事情.所以...

我知道非阻塞应该做什么.我的问题是......为什么不读任何东西!相同的设置在Windows上工作正常,所以所有硬件都工作正常...

这让我疯了!我确定这很简单!我甚至试图摆脱O_NONBLOCK,看看我什么时候收到东西......但没有......

jld*_*ont 11

这个.

EAGAIN使用O_NONBLOCK选择了非阻塞I/O,并且没有数据立即可供读取.

  • 这正是问题,如果有点简洁.我想更广泛的问题是,如果你不准备处理它的行为,你为什么要指定O_NONBLOCK? (6认同)