c - Linux - 串行端口读取返回 EAGAIN

标签 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];

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

int nc = write(hCom, txchar, n);

其中 hCom 是文件描述符(没关系),并且(如我所说)这是有效的。但是......当我之后进行读取时,我从 errno 收到“资源暂时不可用”错误。

我测试了 select 以查看文件描述符何时有某些内容未读取...但它总是超时!

我这样读取数据:

ret = read(hCom, rxchar, n);

而且我总是得到 EAGAIN,我不知道为什么。

更新:

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

我知道非阻塞应该做什么。我的问题是......为什么没有任何东西被阅读!。相同的设置在 Windows 上运行良好,因此所有硬件都运行良好...

这让我抓狂!我敢肯定这很简单!我什至尝试摆脱 O_NONBLOCK 看看我什么时候会收到一些东西......但什么都没有......

最佳答案

阅读this .

EAGAIN Non-blocking I/O has been selected using O_NONBLOCK and no data was immediately available for reading.

关于c - Linux - 串行端口读取返回 EAGAIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1613916/

相关文章:

c - 寻找最小和最大单词的程序

作为命令行参数的 c 套接字端口号是否已更改?

linux - 硬件启动 - 在新板上安装 uboot

Python监控串口(RS-232)握手信号

c - 具有自动目标创建功能的潜在大型项目的 Makefile

c++ - 如何以编程方式将路由添加到网络接口(interface)

linux - 使用 awk 和 sed 消除不需要的输出

android - 如何通过本地网络中的主机名查找IP地址?

c++ - Windows 7/64 中的串行异步 I/O

c++ - 检测移除打开的串口设备(Qt/Windows)