New library: libpidfile.

Pawel Jakub Dawidek pjd at FreeBSD.org
Mon Aug 22 21:30:56 GMT 2005


Hi.

I'd like to commit a small library for handling "pidfiles".

It is something that is used by quite every daemon, but most of them don't
do it right.

Most important thing about this library, is that created pidfile is
flock(2)ed, so we can easly detect is daemon is already running.

Another interesting thing is that I've also modified pkill(1)'s '-F' option
to take advantage of libpidfile and only kill process from the given
pidfile if we cannot flock it. This ensures, that we don't kill some random
process when daemon is already dead.

Libpidfile has four functions to offer, but it will be easiest to just show
an example of use (this is from manual page):

	pid_t otherpid, childpid;

	if (pidfile_open("/var/run/daemon.pid", 0644, &otherpid) == -1) {
		if (errno == EEXIST) {
			errx(EXIT_FAILURE, "Daemon already running, pid: %d.",
			    otherpid);
		}
		/* If we cannot create pidfile from other reasons, only warn. */
		warn("Cannot open or create pidfile");
	}

	if (daemon(0, 0) == -1) {
		warn("Cannot daemonize");
		pidfile_remove(1);
		exit(EXIT_FAILURE);
	}

	pidfile_write();

	for (;;) {
		/* Do work. */
		childpid = fork();
		switch (childpid) {
		case -1:
			syslog(LOG_ERR, "Cannot fork(): %s.", strerror(errno));
			break;
		case 0:
			pidfile_close();
			/* Do child work. */
			break;
		default:
			syslog(LOG_INFO, "Child %d started.", childpid);
			break;
		}
	}

	pidfile_remove(0); /* Not really needed. */
	exit(EXIT_SUCCESS);

As you can see, it easy to use. Note that return values from functions other
than pidfile_open() can be ignored, as they were implemented to handle
previous pidfile_open() failure.

The work is finished. It was implemented in FreeBSD's perforce in
pjd_pidfile branch.
I also converted few daemons:
	- devd(8),
	- cron(8),
	- syslogd(8),
	- moused(8),
	- powerd(8).
Reimplementation of pkill(1)'s '-F' option is also there.

The source code is availabe here:

	http://perforce.freebsd.org/depotTreeBrowser.cgi?FSPC=//depot/user/pjd/pidfile/lib/libpidfile&HIDEDEL=NO

-- 
Pawel Jakub Dawidek                       http://www.wheel.pl
pjd at FreeBSD.org                           http://www.FreeBSD.org
FreeBSD committer                         Am I Evil? Yes, I Am!
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 187 bytes
Desc: not available
Url : http://lists.freebsd.org/pipermail/freebsd-arch/attachments/20050822/1d588555/attachment.bin


More information about the freebsd-arch mailing list