[systemd-devel] How to start a unit right after another unit terminates?

Mantas Mikulėnas grawity at gmail.com
Mon Jul 16 18:55:12 UTC 2018


On Mon, Jul 16, 2018, 21:33 John Ioannidis <systemd-devel at tla.org> wrote:

> Assume I have a one-shot service, *phase1.service*, which runs for a
> while and then terminates. I want to have a *phase2.service* start up
> when phase1 terminates.
>
> I cannot change anything in phase1.service's systemd files or code or
> anything, or I would not be asking this question!
>

Sure you can – systemd has several ways of extending a unit file without
touching the (read-only) original, such as "<unit>.d/*.conf" drop-ins or
"<unit>.wants/" symlinks.

And in the end those are the only direct answer to your question. If
phase1.service needs to trigger phase2.service, the former must have a
dependency (Requires= or Wants=) on the latter. Anything else would be
either a workaround or a hack.


> A dirty workaround is to just have phase2 start before phase1 and run this
> script (wait until phase1 starts up, then wait until it finishes, then do
> its thing):
>

Type=oneshot services are "starting" the entire time the main process is
running, moving to active or inactive only when the process *exits*.

As far as I know, they don't have separate "starts up" and "finishes"
phases, so your description of phase1.service's behavior contradicts
itself. Please clarify this.


>     while ! systemctl status phase1.service > /dev/null
>     do
>       sleep 10 # still waiting for phase1 to start up
>     done
>     while systemctl status phase1.service > /dev/null
>     do
>       sleep 10 # still waiting for phase1 to finish
>     done
>     # now do the phase2 work
>
> There has to be a better way of doing this, but I can't figure it out.
> Google/Bing/SO searches return lots of other workarounds, mostly for user
> sessions, which is not the case here.
>

If phase1.service is truly Type=oneshot, then extending it as follows
should work fine.

    # /etc/systemd/system/phase1.service.d/depend-on-phase2.conf
    [Unit]
    Wants=phase2.service
    Before=phase2.service

If it's not Type=oneshot... sure sounds like it was meant to be.

Unfortunately for all other types (which have a distinct 'stopping' stage)
there's no straightforward answer, although there still are plenty of
better options than "while(sleep 10)".
-- 

Mantas Mikulėnas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.freedesktop.org/archives/systemd-devel/attachments/20180716/a7a45170/attachment.html>


More information about the systemd-devel mailing list