Search code examples
ubuntu-16.04systemdstartupscript

How the stoppage of a systemd service can trigger the stoppage of different one?


I'm creating a systemd service let's call it B on Ubuntu 16.04 which I'd like on every boot to start after a specific service called A and then run a specific script. So far I've created the service unit file which consists of the following fields:

[Unit]
Description=B
After=A.service

[Service]
ExecStart=/opt/B.sh

[Install]
WantedBy=multi-user.target

Furthermore I'd like the stoppage of service A to trigger the stoppage of service B. Is it valid to do it with the following command in the A service unit file

ExecStop=systemctl stop A.service

or is there another way ? If possible I'd like not to change the existing A service file unit.


Solution

  • You can combine two systemd features to solve your problem.

    First, you can use a drop-in file to extend an existing systemd conf file without modifying it. Here's the pattern:

    1. Create /etc/systemd/system/A.d/stop-b.conf.
    2. Add this to it:

    [Service] ExecStopPost=systemctl stop B.service

    That would be if you wanted to stop B when A is stopped. The second feature you see in use is the ExecStopPost= directive, to cause run an additional command when a service is stopped.