1
vim /home/mytest.sh
rm -f /home/mytest/*

I want to write a service to execute the remove action.
My expections:
sudo systemctl stop mytest can delete files in /home/mytest
sudo systemctl start mytest do nothing.

Edit my service file.

sudo vim /etc/systemd/system/mytest.service
[Unit]
Description=delete file

[Service]
Type=oneshot
ExecStart=/bin/true
ExecStop=/bin/bash /home/mytest.sh

[Install]
WantedBy=multi-user.target

Enable it.

sudo systemctl enable mytest

Now i found a strange action for mytest service.

sudo systemctl start mytest can delete files in /home/mytest
sudo systemctl stop mytest do nothing.

Why? Pleas give a explanation in detail.

4

This is explained in detail in the systemd service documentation, but you pretty much need to read all of it to understand what’s going on. The most pertinent part in this case is example 3; from that, the reader can gather that a oneshot service as you’ve declared it never becomes active, so its stop action will be run once its start action completes.

To achieve what you’re after, you need a oneshot service which nevertheless becomes active:

[Unit]
Description=delete file

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStop=/bin/bash /home/mytest.sh

[Install]
WantedBy=multi-user.target
0

Basically, systemd tracks all the processes it starts through cgroups, and unless you specify RemainAfterExit=yes, it won't maintain the state information "yes, mytest.service was run and should be considered still enabled although there are no processes left in its cgroup."

Without RemainAfterExit=yes, systemctl stop mytest makes systemd just take a look at the systemd/system.slice/mytest.service cgroup, and as there are no processes in it, it just thinks "it seems to be already stopped, so... nothing to do there!"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.