简体   繁体   English

C:读取 function 未在断开的串行 USB 设备上返回错误

[英]C: Read function does not return error on disconnected serial USB device

I have a C application which opens a /dev/ttyUSB* port我有一个 C 应用程序,它打开了一个 /dev/ttyUSB* 端口

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

The port is opened, and I receive data.端口打开,我收到数据。 If however the USB device is disconnected later on, and I call the read function:但是,如果稍后 USB 设备断开连接,我调用读取 function:

nRead = _read(fd, buffer, length);

nRead will return 0. I would expect that it should return a negative number to indicate an error (that the device is no longer available). nRead 将返回 0。我希望它返回一个负数以指示错误(设备不再可用)。

How do I detect that the opened device was disconnected?如何检测打开的设备已断开连接?

When read() returns zero, you can call stat() on the device filename.read()返回零时,您可以对设备文件名调用stat() If the USB device is disconnected, the device node has vanished, and stat() will return -1 with errno==ENOENT.如果 USB 设备断开连接,则设备节点已消失,stat() 将返回 -1,errno==ENOENT。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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