7

I'm wondering how to stop all units that are grouped together by the same target.

My setup is as follows. I have several unit config files that read:

[Unit]
...

[Service]
...

[Install]
WantedBy=mycustom.target

When I run

# systemctl start mycustom.target

Those units that "are wanted by" mycustom.target start correctly. Now, I would also like to be able stop all units that are wanted by mycustom.target. I tried:

# systemctl stop mycustom.target

This doesn't do anything though. Is there a way to make this work without having to stop all units that are (explicitly) wanted by the same target?

6

There are two ways: an implicit and an explicit.

First way — StopWhenUnneeded=

The first way is to use the StopWhenUnneeded= directive. If a unit has StopWhenUnneeded=yes, it will be automatically stopped when there becomes no active unit which Wants=/Requires= the unit in question. Hence:

  • this will only work if these units are WantedBy= only by mycustom.target;
  • you will be unable to start any of these units manually (i. e. systemctl start myunit.service will start it and immediately stop it afterwards).

Second way — a shell pipeline

The second way is to construct a simple shell pipeline, using systemctl show -p to extract the dependency list of mycustom.target.

More specifically, systemctl show UNIT will show all properties of a unit in a KEY=VALUE form, and systemctl show -p PROPERTIES UNIT will do the same, limiting the set of shown properties. So:

systemctl stop -- $(systemctl show -p Wants mycustom.target | cut -d= -f2)
20

Use the PartOf= directive.

Configures dependencies similar to Requires=, but limited to stopping and restarting of units. When systemd stops or restarts the units listed here, the action is propagated to this unit. Note that this is a one-way dependency — changes to this unit do not affect the listed units.

PartOf=mycustom.target

  • 1
    Should I combine it with StopWhenUnneeded or is it implied? – PSSGCSim Nov 1 '17 at 6:56
  • It seems that StopWhenUnneeded is not necessary when using PartOf. @PSSGCSim – Gary van der Merwe Oct 2 '18 at 13:26

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.