What’s the best way to remove pid files before starting a service

servicessystemd

I have a service that does not always remove its pid files when shutting down. So when it goes to start up again it fails. My system is a RHEL 7.2 system and what I want to do is have the system look for the file before starting it up and remove it if found. I need to do all of this with systemctl, or it needs to happen before someone runs systemctl start <service>. I have the command I want to use I am just not sure how to integrate that with systemctl for a seamless process. Here is the command:

[ -f /var/run/dir/file.pid ] && echo "Found and removing" && rm -f /var/run/dir/file.pid || echo "Not Found"

Is it possible to stick this inside of the service file that's located in /usr/lib/systemd/system/ ? If so, where would I place it? Here is the contents of the file it would need to go in. We will call it dns.service.

[Unit]
Description=DNS daemon
BindTo=dns.service
After=syslog.target network.target dns.service
ConditionPathExists=/etc/dns/dns.conf

[Service]
Type=forking
EnvironmentFile=/etc/sysconfig/dns
ExecStart=/usr/sbin/dns -u dns -g dns -f   /etc/dns/dns.conf -d -P 17500
Restart=on-abort

[Install]
WantedBy=network.target

Does this seem like the right way to accomplish this or is there a better way?

Best Answer

Custom services should stay in /etc/systemd/system.

Since you are doing forking, what I would do is use the PIDFile= directive. When the service is stopped, it will delete the file. However, on startup, it will not write to the file. It's up to your service to write to it. The recommended place to have it write to is /run.