3

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?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
user53029
  • 2,813

1 Answers1

5

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.

Sokel
  • 1,964
  • Actually this turned out to be not a problem with the pid files but rather the folder they were in. I was able to resolve this by using the ExecStartPre directive to point to a script which then removed the folder. I went ahead and one-upped your answer though for the PIDFile tip. – user53029 Jan 18 '16 at 19:40
  • @sokel what about power failure?the case the service on boot doesn't start as the orphaned pid exist :) best is to make a pre script to check if pid file PID PROCESS exist if not delete file ..... like https://serverfault.com/questions/743705/how-properly-handle-deletion-of-pid-file-in-service-script#answer-74373 – ceph3us Feb 27 '22 at 19:18
  • @ceph3us /run, in majority of cases, is ephemeral (tmpfs). this means on power failure, regular restart, regular shutdown, /run and its contents will go away and start fresh on system start. A PID file really should not exist outside of /run. – Sokel Feb 28 '22 at 20:07