Search code examples
rubylinuxdbuslibusb

How to achieve realtime usb storage detection with Ruby on Linux?


I am thinking ruby-dbus could be the right solution, but I cannot seem to find any examples of how to detect in realtime, whenever a storage device is connected to the Linux machine. Anyone have such an example?


Solution

  • There seems to be numerous different approaches you could take.
    Here's a Ruby implementation I found that links into libusb with Ruby FFI.

    What's good about this is that libusb supports hotplug notifications, so this could be something that does what you need:
    http://libusb.sourceforge.net/api-1.0/hotplug.html

    From the libusb Ruby docs:

    Device hotplug support

    Support for device hotplugging can be used, if LIBUSB.has_capability?(:CAP_HAS_HOTPLUG) returns true. This requires libusb-1.0.16 or newer on Linux or MacOS. Windows support is still on the way.

    A hotplug event handler can be registered with {LIBUSB::Context#on_hotplug_event}. You then need to call {LIBUSB::Context#handle_events} in order to receive any events. This can be done as blocking calls (possibly in it's own thread) or by using {LIBUSB::Context#pollfds} to detect any events to handle.