Are Pid-Files Still Flawed When Doing It 'Right'

What is a .pid file and what does it contain?

The pid files contains the process id (a number) of a given program. For example, Apache HTTPD may write its main process number to a pid file - which is a regular text file, nothing more than that - and later use the information there contained to stop itself. You can also use that information to kill the process yourself, using cat filename.pid | xargs kill

Must my pidfile be located in /var/run?

I wouldn't put a pidfile under an application installation directory such as /opt/my_app/whatever. This directory could be mounted read-only, could be shared between machines, could be watched by a daemon that treats any change there as a possible break-in attempt…

The normal location for pidfiles is /var/run. Most unices will clean this directory on boot; under Ubuntu this is achieved by /var/run an in-memory filesystem (tmpfs).

If you start your daemon from a script that's running as root, have it create a subdirectory /var/run/gmooredaemon and chown it to the daemon-running user before suing to the user and starting the daemon.

On many modern Linux systems, if you start the daemon from a script or launcher that isn't running as root, you can put the pidfile in /run/user/$UID, which is a per-user equivalent of the traditional /var/run. Note that the root part of the launcher, or a boot script running as root, needs to create the directory (for a human user, the directory is created when the user logs in).

Otherwise, pick a location under /tmp or /var/tmp, but this introduces additional complexity because the pidfile's name can't be uniquely determined if it's in a world-writable directory.

In any case, make it easy (command-line option, plus perhaps a compile-time option) for the distributor or administrator to change the pidfile location.

Kill process by pid file

I believe you are experiencing this because your default shell is dash (the debian almquist shell), but you are using bash syntax. You can specify bash in the shebang line with something like,

#!/usr/bin/env bash

Or, you could use the dash and bash compatible back-tick expression suggested by admdrew in the comments

kill -9 `cat /var/run/myProcess.pid`

Regardless, you can't rely on /bin/sh to be bash.

Stale PID file after reboot

Often, pidfiles are written into /var/run/ or /run/ (on many systems there is a symlink from /var/run to /run so they are the same). See the Filesystem Hierarchy Standard for more. And that /run/ directory is supposed to be cleared early at boot-time (i.e. because it is mounted as tmpfs), so it won't survive a reboot. See also the Linux Standard Base 4.1 specification.

Hence you should not care about stale pidfiles. This should not happen, and if it does it probably is because the sysadmin messed something up badly. I would just exit with some kind of an error message if that pidfile already exists.



Related Topics



Leave a reply



Submit