Why do daemons store their PID (process id) in a file

daemonprocess

Within my systems /run directory I have a bunch of files that have *.pid extensions and store the process id of running daemons, i.e.

% ls -1 /run/*.pid                    
acpid.pid
crond.pid
dhclient-wlp2s0.pid
irqbalance.pid
lightdm.pid
nginx.pid
rsyslogd.pid

And I have generally noticed this is something many other daemons do and that daemon management scripts in /etc/init.d/* will read in the pid from the last running instance and reuse that on starting a new instance.
Why? why not just start the daemon and give it a new pid?
Are there other programs e.g. rsyslog, that are expecting that daemon to have that identifier and would be confused if a different program was using that pid?

Best Answer

For many daemons, only one instance of the daemon should be running on a system at any one time. In this use case, the daemon typically stores its PID in a well known directory (on Linux, currently /run, previously /var/run) to indicate that an instance of the daemon is running.

If you attempt to invoke a second instance of such a daemon, the newly invoked daemon checks for an existing entry (think of it as a lock file) under /run and exits if found.

If the daemon is restarted then the PID of the new instance is written to the file. The new instance gets its own PID, there's no way to launch a process with a given PID.

The PID file is also used to determine what process to kill to stop the daemon.

Related Question