Runcheckdir now works as a well-behaved system daemon master
authorChip Black <bytex64@bytex64.net>
Tue, 19 Aug 2008 08:56:15 +0000 (03:56 -0500)
committerChip Black <bytex64@bytex64.net>
Tue, 19 Aug 2008 08:56:15 +0000 (03:56 -0500)
runcheckdir

index 535fa68..15d7762 100755 (executable)
@@ -1,7 +1,23 @@
 #!/usr/bin/perl
+use Getopt::Long;
+use Cwd qw/abs_path/;
+use POSIX qw/setsid setuid setgid/;
 use strict;
 
-my $dir = shift;
+my ($nodaemon, $verbose, $pidfile, $logfile, $user, $group, $uid, $gid);
+$pidfile = '/var/run/runcheckdir.pid';
+$logfile = '/var/log/runcheckdir.log';
+
+GetOptions(
+       "nodaemon" => \$nodaemon,
+       "verbose"  => \$verbose,
+       "pidfile=s"  => \$pidfile,
+       "logfile=s"  => \$logfile,
+       "user=s"  => \$user,
+       "group=s"  => \$group,
+);
+
+my $dir = abs_path(shift);
 unless ($dir) {
        print "No directory specified\n";
        exit 1;
@@ -11,6 +27,40 @@ unless (-d $dir) {
        exit 1;
 }
 
+$uid = (getpwnam($user))[2] if $user;
+$gid = (getpwnam($group))[3] if $group;
+
+sub daemonize {
+       if (fork()) {
+               exit 0;
+       }
+       setsid();
+
+       umask 027;
+       if (open STDOUT, ">>$logfile") {
+               open STDERR, ">>$logfile";
+               chown $uid, $gid, $logfile;
+       } else {
+               print "WARNING: Could not open logfile. You will get NO error output.\n";
+               open STDOUT, ">/dev/null";
+               open STDERR, ">/dev/null";
+       }
+       open STDIN, "/dev/null";
+
+       open PID, ">$pidfile" or warn "Could not write PID file\n";
+       print PID "$$\n";
+       close PID;
+       chown $uid, $gid, $pidfile;
+
+       chdir '/';
+       print "Daemon started at ",scalar gmtime(),"\n";
+}
+
+daemonize unless $nodaemon;
+
+setuid($uid) if $uid;
+setgid($uid) if $gid;
+
 $|++;
 
 while (1) {
@@ -22,7 +72,7 @@ while (1) {
                        next;
                }
                print "Running check $dir/$d: ";
-               system("runcheckdir $dir/$d");
+               system("runcheck $dir/$d");
                my $exitstatus = $? >> 8;
                if ($exitstatus) {
                        print "FAILURE\n";