【问题标题】:C: Read function does not return error on disconnected serial USB deviceC:读取功能在断开的串行 USB 设备上不返回错误
【发布时间】:2020-10-24 14:02:10
【问题描述】:

我有一个打开 /dev/ttyUSB* 端口的 C 应用程序

    fd = open(portName.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK);
    options.c_cflag |= (CLOCAL | CREAD);
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_iflag &= (tcflag_t) ~(INLCR | IGNCR | ICRNL | IGNBRK);
    options.c_oflag &= (tcflag_t) ~(OPOST);
    options.c_cflag |= CS8;
    options.c_cflag |= CRTSCTS;
    options.c_lflag &= ~(ICANON | ECHO | ISIG);
    tcsetattr(fd, TCSANOW, &options);
    struct serial_struct kernel_serial_settings;
    if (ioctl(fd, TIOCGSERIAL, &kernel_serial_settings) == 0) {
                kernel_serial_settings.flags |= ASYNC_LOW_LATENCY;
                kernel_serial_settings..
                ioctl(fd, TIOCSSERIAL, &kernel_serial_settings);
    }

端口打开,我接收数据。但是,如果 USB 设备稍后断开连接,我调用读取函数:

nRead = _read(fd, buffer, length);

nRead 将返回 0。我希望它应该返回一个负数来指示错误(设备不再可用)。

如何检测打开的设备已断开连接?

【问题讨论】:

    标签: c linux serial-port


    【解决方案1】:

    read() 返回零时,您可以在设备文件名上调用stat()。如果 USB 设备断开连接,则设备节点已消失,stat() 将返回 -1 且 errno==ENOENT。

    【讨论】:

    • @ryyker 我认为确实如此-问题实际上是“如何检测到打开的设备已断开连接?”如果stat()ENOENT 出错,则字面意思是“它不存在”。由于它之前存在,而现在不存在,“断开连接”是从该结果中做出的一个很好的推论。而且您可能只在文件描述符上使用fstat()。这类似于当 TCP 连接断开时从read() 获取0
    • @AndrewHenle - 谢谢。很好的解释。
    猜你喜欢
    • 2021-09-04
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    相关资源
    最近更新 更多