[systemd-devel] At wits end... need to execute a script prior to anything getting killed/changed on reboot/shutdown
Lennart Poettering
lennart at poettering.net
Thu Jan 17 11:50:07 UTC 2019
On Mi, 16.01.19 12:40, Christopher Cox (ccox at endlessnow.com) wrote:
> I need to be able to execute a script before anything gets shutdown. That
> is, when somebody does a "reboot", "shutdown" or "poweroff", I need this
> script to run first, and for it to finish before everything gets
> whacked.
Well, systemd doesn't know a concept of "before all" and "after all",
as a unit marked that way would have to be the only one, and what do
you do if multiple units are marked that way? Hence, systemd generally
allows you to order units after or before specific other units, but
there are no absolutes like "after all" or "before all".
If you want to define a unit that runs code during shutdown the best
approach is to make it a unit that gets started at boot, and then only
uses ExecStop= (but not necessarily ExecStart=).
Note that the shutdown order of units is generally the inverse of the
startup order. Hence if you want unit A to stop before unit B, then
you have to declare in A "After=B", so that A gets started *after*
unit B, and thus stopped before B, as you need it here.
Usually a system boots into multi-user.target or graphical.target (or
generically default.target), and these are the last (or close to last)
units that are reached. Due to the rule of "stop order is inverted
start order" this also means these targets are the first ones to be
stopped again when the system goes down.
With that you can now put together a unit that is terminated
relatively early on during shutdown: just make it
"After=multi-user.target graphical.target default.target", so that it
gets activated at boot very late, and thus deactivated at shutdown
very early.
> [Unit]
> Description=my-service save status
> DefaultDependencies=no
No need to turn off default dependencies.
> Before=reboot.target shutdown.target
> Conflicts=reboot.target shutdown.target
These two lines are unnecessary.
> [Service]
> Type=oneshot
> RemainAfterExit=yes
> ExecStart=/bin/true
This line is unnecessary on any remotely recent systemd version.
> ExecStop=/usr/local/bin/my-service.sh save
> StandardOutput=journal
This line is redundant, as it is the implied default.
> [Install]
> WantedBy=multi-user.target
Lennart
--
Lennart Poettering, Red Hat
More information about the systemd-devel
mailing list