I have a C application which opens a /dev/ttyUSB* port
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:
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).
How do I detect that the opened device was disconnected?
When read() returns zero, you can call stat() on the device filename. If the USB device is disconnected, the device node has vanished, and stat() will return -1 with errno==ENOENT.