Course contentsShow
← Linux
Lesson 1291 of 1,81911. Automation and System SchedulingFree lesson

Integrating Systemd with D-Bus Signals

Create custom automation workflows driven by D-Bus system messages.

In this lesson, you will learn how to trigger systemd services dynamically based on arbitrary D-Bus signals, moving beyond static file paths and timers.

Beyond File and Time Triggers

Up until now, you have used Path units to react to filesystem changes and Timer units to handle periodic execution. However, many modern Linux events—such as a power state change, a specific application launching, or a hardware event—are broadcast via the D-Bus system bus. While systemd doesn't provide a native "D-Bus listener" unit type in the same way it does for paths, you can integrate D-Bus signals into your automation workflow by creating a "bridge" process.

The Bridge Pattern

The most robust way to trigger a systemd service from a D-Bus signal is to run a lightweight listener script that monitors the bus and executes systemctl start when a specific signal is detected.

Consider a scenario where you want to back up a specific directory the moment a laptop detects that it is connected to a specific corporate network (signaled via NetworkManager on D-Bus). You can use dbus-monitor to identify the signal path and then use a small loop to react to it:

# Example logic for a listener script
dbus-monitor --system "type='signal',member='StateChanged',interface='org.freedesktop.NetworkManager'" | \
while read line; do
    if echo "$line" | grep -q "connected"; then
        systemctl start backup-job.service
    fi
done

Why Use D-Bus Integration?

  1. Event-Driven Efficiency: Unlike polling a file or a clock, your script sleeps until the system bus pushes the event to you.
  2. System Context: You can react to signals from any service running on the system bus (e.g., Logind, NetworkManager, or BlueZ).
  3. Decoupling: The service doing the work remains separate from the logic monitoring the system state.

When implementing this, ensure your listener script runs as a persistent systemd service itself, using Restart=always to ensure it survives crashes. This turns the listener into a reliable daemon that acts as a sensor, bridging the gap between raw D-Bus broadcasts and your managed automation tasks.

Key Takeaway: By using a lightweight listener script as a systemd service, you can translate arbitrary D-Bus broadcast signals into triggers for your own automated systemd workflows.