Main Content

What are .pid files?

Archive - Originally posted on "The Horse's Mouth" - 2010-10-23 08:03:30 - Graham Ellis

wizard:run graham$ ls *.pid
DirectoryService.pid
configd.pid
diskarbitrationd.pid
hdiejectd.pid
httpd.pid
mds.pid
ntpd.pid
racoon.pid
syslog.pid
wizard:run graham$


When a process that needs to be contacted / alerted by other processes is started, it often records its process id (PID) into a ".pid file" so that those other processes know where to find it. The files above are form the /var/run directory on my OS X machine and point to system daemons, but it's a scheme that you may use for your own service processes (daemons) too. Have a look at these files ... and you'll just find a number in each of them.

Here's an example of how a newly starting daemon can log its pid (in Perl):
  open(FH,">","/var/run/nonfat.pid") and print FH "$$\n" and close FH;

And then how another process can check its most recent process ID, and whether it's running:
  open(FH,"/var/run/nonfat.pid");
  chomp($nfpid = <FH>);
  if ( kill 0,$nfpid ) { ...


Perl's kill function isn't as dramatic as it sounds - I sometime find that my classes are surprised to learn that killing is not always fatal. It should, really, have been called the "signal" command and with a zero first parameter it doesn't even send a signal - it just checks to see whether the process of the particular ID is there and running.

Once you've established that a process you want to alert is running, you can send it a proper signal:
  kill "USR1",$nfpid;

Source code examples ... [sending signal] and [receiving and handling signals].