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

Assume the following situation on Linux:

The process is continuously read from the USB-serial converter ( /dev/ttyUSB0 ). This device is suddenly disconnected from the network and reconnected (or for some reason reboots). The process continues to have a valid file descriptor for /dev/ttyUSB0 , but will not receive any data from the device unless the process reopens the device (because udev deleted and re-created the node device).

Is there a direct way to detect such a situation (i.e. not indirectly by detecting a timeout in the data stream) so that the process knows that it must reopen the device? Would it be reliable to track the modification time of /dev/ttyUSB0 with stat() ?

Additional Information:

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

/dev is tmpfs managed by udev .

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

+4
source share
3 answers

If the USB device is disconnected from the network, operations with the device will begin with a -EIO error; You can detect this and take appropriate action.

+1
source

I think that FAM or gamin detect these events.

0
source

If the node device is actually being removed and recreated (which I believe if you have udev) then you should be able to use the inode number to tell when this will happen.

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

And let me know if this really works. :-)

0
source

All Articles