What is udev for

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2024-11-21

udev is the Linux subsystem that supplies your computer with device events. In plain English, that means it detects when you have things plugged into your computer, like network cards, external hard drives (including USB thumb drives), mouses, keyboards, gamepads, DVD-ROM drives, and so on.

Additionally, info about that particular device (name, manufacturer, etc.) is available for distinguishing between items.

See the info the udev system sees real-time

$ udevadm monitor

Then plug devices in and see what happens

Example Use-cases

Use-case 1: Backup files when a certain drive is plugged in

You need two parts

  1. A set of rules to match, contained within a dedicated file within /etc/udev/rules.d
# e.g.`/etc/udev/rules.d/thumbnail-backup.rules`
SUBSYSTEM=="block", ATTRS{idVendor}=="03f0", ACTION=="add", SYMLINK+="safety%n"
SUBSYSTEM=="block", ATTRS{idVendor}=="03f0", ACTION=="add", RUN+="/usr/local/bin/trigger.sh"

The first line detects my thumb drive matching certain attributes, then assigns the thumb drive a symlink within the device tree. The symlink it assigns is "safety%n". The %n is a udev macro that resolves to whatever number the kernel gives to the device, such as sdb1, sdb2, sdb3, and so on. So %n would be the 1 or the 2 or the 3.

  1. The script that gets triggered when the rules match (/usr/local/bin/trigger.sh) above
# Example script
mount /dev/safety1 /mnt/hd
sleep 2
rsync -az /mnt/hd/ /home/seth/backups/ && umount /dev/safety1

Use-case 2: load CUPS drivers in systemd as soon as a printer is connected

No specifics here yet.

Udev vs dev

/dev is a directory. udev is a service that puts entries in that directory.

'udev' is a system (a daemon and filesystem) that automagically populates the contents of /dev with device files that reflect the hardware actually installed on your machine. With udev, if you plug in a device (like a USB drive) the entry appears under /dev for the device.

Resources