linuxsystemdsystemctl

Prevent a service from stopping if certain conditions apply


I don't want the service to stop when using systemctl stop service if certain conditions apply.

Is there a way to check beforehand and then just return an errorcode?

I wrote a custom script for ExecStop that checks for those conditions and then return an error. The script works, it returns the correct errorcode and then the service gets killed regardless.

This is how I configured my service:

[Service]
Type=simple
User=root
ExecStop=/bin/bash /opt/service.stop

This is my script:

#!/usr/bin/env bash
# Version: 1.0.0


## RUN SCRIPT ##

# how many active connections
show_con

if [ "${connectionsCount}" -gt 0 ]
    exit 1
else
    stop_service
fi

Solution

  • I found the solution:

    in [service] you have to add KillMode=none so it looks like this:

    [Service]
    KillMode=none
    Type=simple
    User=root
    ExecStart=/bin/bash /opt/service.start
    ExecStop=/bin/bash /opt/service.stop

    Then it won't kill the process after running the bash script.