Reference for proper handling of PID file on Unix

First off, on all modern UNIXes /var/run does not persist across reboots.

The general method of handling the PID file is to create it during initialization and delete it from any exit, either normal or signal handler.

There are two canonical ways to atomically create/check for the file. The main one these days is to open it with the O_EXCL flag: if the file already exists, the call fails. The old way (mandatory on systems without O_EXCL) is to create it with a random name and link to it. The link will fail if the target exists.

Leave a Comment