Course contentsShow
← Linux
Lesson 624 of 1,8196. Systemd Internals and Unit OrchestrationFree lesson

Hardware Monitoring Units

Use device units to trigger services when specific hardware bus events occur.

In this lesson, you will learn how to use systemd device units to automatically trigger services when specific hardware, such as a USB drive or a specialized interface, is connected to your system.

How Hardware Becomes a Unit

In Linux, udev monitors the kernel for hardware events. When you plug in a device, udev detects it and creates a device node. systemd automatically translates these kernel events into Device Units (.device files).

You don't need to manually create these unit files; systemd generates them dynamically based on the hardware path. You can see your current hardware units by running systemctl list-units --type=device.

Orchestrating Services with Hardware

The power of these units lies in the BindsTo and After directives. By linking a service to a specific device unit, you can ensure a backup script, a mount operation, or a diagnostic tool only runs when that specific piece of hardware is present.

For example, imagine you have a backup drive. You want a service called backup-data.service to start only when that drive is plugged in:

[Unit]
Description=Run Backup on USB Drive
BindsTo=dev-sdb1.device
After=dev-sdb1.device

[Service]
ExecStart=/usr/local/bin/backup-script.sh

Why BindsTo?

Using BindsTo is crucial here because it creates a strict dependency. If you unplug the hardware, systemd will immediately stop the associated service. This prevents your scripts from hanging or erroring out when they attempt to write to a drive that has been physically removed.

The device unit name is derived from the device path; for instance, /dev/sdb1 becomes dev-sdb1.device. You can find the exact name for your hardware by running systemctl list-units --type=device, which is particularly helpful if your device name is a complex UUID-based path.

By leveraging these units, your system becomes reactive—adjusting its workload based on the physical state of your hardware rather than relying on constant, wasteful polling or manual intervention.

Key Takeaway: Use device units with the BindsTo directive to create hardware-aware services that automatically launch upon device insertion and safely terminate upon removal.