1

Similar, but not identical to Run script at shutdown/reboot with systemd:

I want to run a custom process using systemd when the system is going down (shutdown or reboot, maybe panic also), and when the system is booting. Both actions should be run as early as possible.

Obviously the Type of service will be a oneshot, but I'm unsure about the rest (Wants, Before, After, WantedBy, etc.).

As my process needs the journal, I had added (among others):

[Unit]
DefaultDependencies=no
Wants=syslog.target
After=local-fs.target exit.target
Before=multi-user-target

[Service]
Type=oneshot
RemainAfterExit=no

[Install]
WantedBy=multi-user.target

When having enabled the service, my program is started (via ExecStart=) after local filesystems are mounted, but it is immediately started again (via ExecStop=) before temporary files are being created. On reboot it was not started at all.

1 Answer 1

1

After multiple iterations I found this solution involving two units; one used for booting, and another used for shutting down:

# /etc/systemd/system/log-start-test.service
[Unit]
Description=Test Start log entries
Documentation=man:logger(1)
Documentation=https://www.freedesktop.org/software/systemd/man/bootup.html
DefaultDependencies=no
After=local-fs.target
Before=sysinit.target
Requires=local-fs.target
ConditionPathExists=/usr/bin/logger

[Service]
Type=oneshot
TimeoutSec=5
ExecStart=/usr/bin/logger -p user.notice "Starting test..."

[Install]
WantedBy=sysinit.target

The start is logged shortly after the local filesystems were mounted (as requested).

# /etc/systemd/system/log-stop-test.service
[Unit]
Description=Test Stop log entries
Documentation=man:logger(1)
Documentation=https://www.freedesktop.org/software/systemd/man/bootup.html
DefaultDependencies=no
After=default.target
Requires=local-fs.target
ConditionPathExists=/usr/bin/logger

[Service]
Type=oneshot
TimeoutSec=5
RemainAfterExit=yes
ExecStop=/usr/bin/logger -p user.notice "Stopping Test..."

[Install]
WantedBy=default.target

The stop message is logged after the first few serviced were terminated (concurrently ran with them I guess).

The TimeoutSec=5 is there, just to make sure a hanging process won't prevent booting or stopping, and most likely it makes no sense for logger.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .