开发者

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 开发者_JAVA百科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.


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


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


I think FAM or gamin will detect these events.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜