5

Assume the following situation under Linux:

A process is continuously reading from an USB-serial converter device (/dev/ttyUSB0). That device is suddenly unplugged and plugged in again (or is resetting itself for some reason). The process continues to have a valid file handle for /dev/ttyUSB0 but won't receive any data from the device unless the process re-opens the device (because udev has deleted and re-created the device node).

Is there a direct way to detect such a situation (ie. not indirectly by detecting a timeout in data flow) so that the process knows it has to re-open the device? Would it be reliable to monitor the modification time of /dev/ttyUSB0 using stat()?

Additional details:

The process opens the device file by using the standard open() function.

/dev is a tmpfs controlled by udev.

Note: I do not want to use any udev rules for this and prefer a solution implemented directly in the process.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Udo G
  • 12,572
  • 13
  • 56
  • 89

3 Answers3

1

If a USB device is hot-unplugged, operations on the device will begin failing with -EIO; you can detect this and take appropriate action.

bdonlan
  • 224,562
  • 31
  • 268
  • 324
  • Thanks, that's right, I'm getting that error after unplugging. Can I safely assume that the file descriptor has become useless when getting EIO or are there situations that cause a **temporary** EIO and where the file descriptor becomes functional later? Currently I have implemented a logic that completely closes, re-opens and re-initializes the device (a modem) after a read() with EIO. – Udo G Jul 12 '11 at 14:33
  • @Udo: It's _possible_ - for example, if your hard disk is having some kind of transient mechanical error, you might get an -EIO on one read, the hard disk recovers, and the next read succeeds. However it's unlikely, and reinitializing the device is probably the right thing to do if you see an -EIO. – bdonlan Jul 12 '11 at 14:35
1

If the device node is actually being removed and re-created (which I believe it is if you have udev), then you should be able to use the inode number to tell when this happens.

Just call fstat() on your open file descriptor, stat() on /dev/ttyUSB0, and compare the st_ino fields of the two struct stats.

And let me know if it actually works. :-)

Nemo
  • 70,042
  • 10
  • 116
  • 153
  • The strategy works for me. I implemented it in python: https://github.com/hrchu/python-scsi/blob/b4e796bd92c4af9501ac597eda87840db4c0f0e5/pyscsi/pyscsi/scsi_device.py#L106 – petertc Mar 20 '19 at 06:49
  • Update: inode of device file does not change for certain device types. In my box, device file of usb mass storage devices always have the same inode even after replugged. – petertc Mar 21 '19 at 00:54
0

I think FAM or gamin will detect these events.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176