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.

1

3 Answers 3

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.

2
  • 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, 2011 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, 2011 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. :-)

2
  • The strategy works for me. I implemented it in python: github.com/hrchu/python-scsi/blob/…
    – petertc
    Mar 20, 2019 at 6: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, 2019 at 0:54
0

I think FAM or gamin will detect these events.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.