Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if an open file/device has been replaced/deleted

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.

like image 678
Udo G Avatar asked Nov 04 '22 19:11

Udo G


2 Answers

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

like image 104
bdonlan Avatar answered Nov 09 '22 06:11

bdonlan


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. :-)

like image 30
Nemo Avatar answered Nov 09 '22 05:11

Nemo