Skip to content

Commit

Permalink
Update to OpenBSD pidfile.c v1.11 with libite ext.
Browse files Browse the repository at this point in the history
This patch updates the OpenBSD pidfile() implementation to v1.11 and
adds libite (-lite) extensions to make pidfile() idempotent as well as
use `utimensat()` to update the mtime if called multiple times.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
  • Loading branch information
troglobit committed Jul 4, 2016
1 parent 6171e52 commit 7462761
Showing 1 changed file with 29 additions and 7 deletions.
36 changes: 29 additions & 7 deletions pidfile.c
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* $OpenBSD: pidfile.c,v 1.10 2014/06/30 00:26:22 deraadt Exp $ */
/* Updated by troglobit for libite/finit/uftpd/smcroute projects 2016/07/04 */
/* $OpenBSD: pidfile.c,v 1.11 2015/06/03 02:24:36 millert Exp $ */
/* $NetBSD: pidfile.c,v 1.4 2001/02/19 22:43:42 cgd Exp $ */

/*-
Expand Down Expand Up @@ -31,38 +32,51 @@
*/

#include "config.h"
#include <sys/stat.h> /* utimensat() */
#include <sys/time.h> /* utimensat() on *BSD */
#include <sys/types.h>
#include <errno.h>
#include <paths.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static char *pidfile_path;
#ifndef pidfile
static char *pidfile_path = NULL;
static pid_t pidfile_pid;

static void pidfile_cleanup(void);

const char *__pidfile_path = _PATH_VARRUN; /* Note: includes trailing slash '/' */
const char *__pidfile_name = NULL;
extern char *__progname;

int
pidfile(const char *basename)
{
int save_errno, result;
int save_errno;
int atexit_already;
pid_t pid;
FILE *f;

if (basename == NULL)
basename = __progname;

pid = getpid();
atexit_already = 0;

if (pidfile_path != NULL) {
if (pid == pidfile_pid) {
utimensat(0, pidfile_path, NULL, 0);
return (0);
}
free(pidfile_path);
pidfile_path = NULL;
__pidfile_name = NULL;
atexit_already = 1;
}

/* _PATH_VARRUN includes trailing / */
result = asprintf(&pidfile_path, "%s%s.pid", _PATH_VARRUN, basename);
if (result == -1 || pidfile_path == NULL)
if (asprintf(&pidfile_path, "%s%s.pid", __pidfile_path, basename) == -1)
return (-1);

if ((f = fopen(pidfile_path, "w")) == NULL) {
Expand All @@ -73,7 +87,6 @@ pidfile(const char *basename)
return (-1);
}

pid = getpid();
if (fprintf(f, "%ld\n", (long)pid) <= 0 || fflush(f) != 0) {
save_errno = errno;
(void) fclose(f);
Expand All @@ -85,6 +98,13 @@ pidfile(const char *basename)
}
(void) fclose(f);

/*
* LITE extension, no need to set up another atexit() handler
* if user only called us to update the mtime of the PID file
*/
if (atexit_already)
return (0);

pidfile_pid = pid;
if (atexit(pidfile_cleanup) < 0) {
save_errno = errno;
Expand All @@ -95,6 +115,7 @@ pidfile(const char *basename)
errno = save_errno;
return (-1);
}
__pidfile_name = pidfile_path;

return (0);
}
Expand All @@ -108,3 +129,4 @@ pidfile_cleanup(void)
pidfile_path = NULL;
}
}
#endif

0 comments on commit 7462761

Please sign in to comment.