From 54c59f46b2797f7689d67f9670ab595b6ef71a44 Mon Sep 17 00:00:00 2001
From: Sergey Ivanov <seriv@cs.umd.edu>
Date: Mon, 16 Nov 2015 17:01:31 -0500
Subject: [PATCH] Systemd require pidfile for forking daemons

Added option -r <pidfile> for resmon.
If none provided it will run without creating pidfile.
If provided, it will try write it's pid into specified file.
Resmon-systemd.service should have this file as an argument for
resmon as a PIDFile option and in ExecStart option.
---
 resmon                           | 14 ++++++++++++--
 resources/resmon-systemd.service |  4 +++-
 2 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/resmon b/resmon
index fd78b85..5bd1cf6 100755
--- a/resmon
+++ b/resmon
@@ -13,7 +13,7 @@ use POSIX qw( :sys_wait_h setsid );
 use Getopt::Long;
 use Data::Dumper;
 use vars qw($config_file $debug $status_file $interface $port $config
-$status $update);
+$status $update $pid_file);
 
 use Resmon::Config;
 use Resmon::ExtComm;
@@ -26,6 +26,7 @@ GetOptions(
     "d"   => \$debug,
     "f=s" => \$status_file,
     "u"   => \$update,
+    "r=s" => \$pid_file,
 );
 
 if ($update) {
@@ -42,6 +43,7 @@ sub configure {
     $config->{statusfile} = $status_file if($status_file);
     $config->{port} = $port if($port);
     $config->{interface} = $interface if($interface);
+    $config->{pidfile} = $pid_file if ($pid_file);
 }
 
 configure();
@@ -77,7 +79,15 @@ unless($debug) {
     open(STDIN, "</dev/null");
     open(STDOUT, ">/dev/null");
     open(STDERR, ">/dev/null");
-    fork && exit;
+    my $pid=fork;
+    if ($pid) {
+      if (my $PIDFILE=$config->{pidfile}) {
+        open(PIDFILE,">$PIDFILE") or die "can't open >$PIDFILE";
+        print PIDFILE $pid;
+        close PIDFILE or die "can't close $PIDFILE";
+      }
+      exit;
+    }
 }
 
 my $list = [];
diff --git a/resources/resmon-systemd.service b/resources/resmon-systemd.service
index 7d6422b..2bc61e0 100644
--- a/resources/resmon-systemd.service
+++ b/resources/resmon-systemd.service
@@ -5,8 +5,10 @@ After=network.target
 
 [Service]
 Type=forking
-ExecStart=/opt/resmon/resmon
+ExecStart=/opt/resmon/resmon -r /run/resmon.pid
 Restart=on-failure
+PIDFile=/run/resmon.pid
+ExecReload=/bin/kill -HUP $MAINPID
 
 [Install]
 WantedBy=multi-user.target
-- 
GitLab