[systemd-devel] Shutdown a specific service in systemd shutdown

Michael Chapman mike at very.puzzling.org
Wed May 25 10:09:50 UTC 2016


On Thu, 19 May 2016, Bao Nguyen wrote:
> Hi everyone,
>
> When the system is shutdown, systemd will terminate all services in
> parallel manner, could you let me know if there is any ways to tell systemd
> to shutdown a specific service first, then shutdown all remaining services?

Hello,

I haven't tested it, but as far as I know all you need to do is ensure 
your special service is After=multi-user.target, i.e.:

   [Unit]
   Description=Some service that must be started late / stopped early
   After=multi-user.target

   [Service]
   # ...

   [Install]
   WantedBy=multi-user.target

A target unit is automatically After= all the units that it Wants=, 
Requires=, etc., but this automatic dependency is *not* added if that 
would create a dependency loop.

So at shutdown systemd knows it needs to stop all services and targets. 
Because your special service is After=multi-user.target, and 
multi-user.target is After= all *other* normal services, everything gets 
ordered correctly: your service is stopped first, then multi-user.target 
is stopped, then all the other services are stopped.

Now, this isn't the *cleanest* solution -- you really want to be specific 
in your service dependencies rather than depending upon a whole target's 
worth of services, and there's always the chance that multi-user.target 
might be stopped some other way before shutdown -- but it does seem as if 
it goes some way to solving your problem.

- Michael


More information about the systemd-devel mailing list