Q:

How to run a daemon only when a specific application is running?

I have a user-space daemon, call it maxwell, that executes various actions based on D-bus signals from another application, call it room. I would like to run maxwell as soon as the user starts room, and stop it when room exits.
I think a launcher script like this would result in the desired behaviour:
#!/bin/sh

systemctl --user start maxwell
room
systemctl --user stop maxwell

but is there a better / standard way to do it, e.g. via systemd itself?
Update: It seems like the functionality I'm looking for is similar to what upstart used to provide with its dbus event. The closest thing that can be achieved with systemd appears to be auto-starting a service which "owns" a certain D-bus name when that name is first used, as per Stephen Kitt's answer; unfortunately, in this case it is room that "owns" the name.

Note: I don't think that this is the same as systemd requires="some non-systemd process"? or, at least, that the answer provided therein works in this case. As far as I understand, using ExecStartPre would simply mark the maxwell unit as failed if room wasn't already running.

A:

systemd supports D-Bus activation, where a service is started to service a D-Bus method call. I’m not sure whether this can be transposed to user services; for system services you create a D-Bus service file:
[D-BUS Service]
Name=your.bus.name
Exec=/path/to/the/daemon
User=root
SystemdService=systemd-service-name.service

and a corresponding systemd service, which has to specify a matching bus name:
[Service]
BusName=your.bus.name

Specifying BusName in this way automatically marks the service as a D-Bus service.
It should be possible to install everything as user services (changing User in the D-Bus service file to match), but I haven’t tried that.

