2025-03-20 19:03:23 +01:00
2025-03-20 19:03:23 +01:00
2025-03-20 19:02:40 +01:00
2025-03-20 19:04:25 +01:00

udev-filter

Super fast and efficient way of only getting udev events you desire.
It provides an efficient way to perform automatic tasks when any device related event occurs, entirely in userspace and without adding any udev rules!

udev-filter listens to events via udevadm monitor -p. It matches the udev events to event properties that are passed as command arguments. When all properties of an event are registered, the program ouputs the name of the event, as defined by the user.

Examples

udev-filter --event=USB_REMOVED ACTION=remove 
USB_REMOVED
USB_REMOVED
...

prints USB_REMOVED any time a USB device is removed. The name after --event can be freely chosen. Another, more useful example might be:

udev-filter --event=YUBIKEY_ADDED ACTION=add ID_USB_VENDOR=Yubico

prints YUBIKEY_ADDED every time a device with vendor id "Yubico" is added.

You can, of course, also listen to many events add once. To combine the previous two:

udev-filter \
    --event=USB_REMOVED ACTION=remove SUBSYSTEM=USB \
    --event=YUBIKEY_ADDED ACTION=add ID_USB_VENDOR=Yubico"

Performing actions on events

To automatically open yubico-authenticator every time a yubikey is connected, create this shell script and run it in the background:

# stdbuf is necessary to force buffer flushing on newlines
stdbuf -oL ./udev-filter --command-add="-s usb" \
    --event=YUBIKEY_ADDED ACTION=add ID_USB_VENDOR=Yubico | \
while read EVENT; do
    # in this example the only possible event is YUBIKEY_ADDED, so the switch-case is not necessary,
    # but it is useful for further expansion
    case $EVENT in
        YUBIKEY_ADDED)
            notify-send "Yubikey Added!"
            { pgrep yubico || yubico-authenticator & }
            ;;
        *)
            notify-send "Unhandled event: $EVENT"
            ;;
    esac
done

Because udev-filter relies on events instead of polling, this script will consume near zero resources. It will only do something whenever a udev event occurs.

To find out which properties you need to query, run udevadm monitor -p. To limit the events to a certain subsystem, add -s <subsystem> to udevadm, and later --command-add="-s <subsystem>" to udev-filter.

Installation

gcc, with glibc++ for C++23 and GNU make are required, which will be available in most modern Linux distributions already.

cd src 
make release

will create ../udev-filter. Copy it anywhere you want, for example ~/.local/bin

Description
Efficient way of performing userspace actions on udev events
Readme GPL-3.0 42 KiB
Languages
C++ 86.3%
Makefile 13.7%