+/* If a pidfile has been configured and that pidfile already exists and is
+ * locked by a running process, returns the pid of the running process.
+ * Otherwise, returns 0. */
+static pid_t
+already_running(void)
+{
+ pid_t pid = 0;
+ if (pidfile) {
+ int fd = open(pidfile, O_RDWR);
+ if (fd >= 0) {
+ struct flock lck;
+ lck.l_type = F_WRLCK;
+ lck.l_whence = SEEK_SET;
+ lck.l_start = 0;
+ lck.l_len = 0;
+ if (fcntl(fd, F_GETLK, &lck) != -1 && lck.l_type != F_UNLCK) {
+ pid = lck.l_pid;
+ }
+ close(fd);
+ }
+ }
+ return pid;
+}
+
+/* If a locked pidfile exists, issue a warning message and, unless
+ * ignore_existing_pidfile() has been called, terminate the program. */
+void
+die_if_already_running(void)
+{
+ pid_t pid = already_running();
+ if (pid) {
+ if (!force) {
+ fatal(0, "%s: already running as pid %ld",
+ get_pidfile(), (long int) pid);
+ } else {
+ VLOG_WARN("%s: %s already running as pid %ld",
+ get_pidfile(), program_name, (long int) pid);
+ }
+ }
+}
+