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.

Description=DNS daemon
After=syslog.target network.target dns.service

ExecStart=/usr/sbin/dns -u dns -g dns -f   /etc/dns/dns.conf -d -P 17500


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

1 Answer 1


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.

  • 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, 2016 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 serverfault.com/questions/743705/…
    – ceph3us
    Feb 27, 2022 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, 2022 at 20:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .