March 2005

Perl Daemon Part II: Options and Usage

Now the earlier Perl Daemon script picks up a few options, arguments and a simple usage message.

Added Options

The three options that made the most sense to add were:

  • Mount point to be checked.
  • Interval in seconds to check.
  • Logfile location.

The interval and logfile still have defaults. The default for the interval is 300 seconds (or once every five minutes) and the logfile in /tmp/mntchk.log.

In addition to options with arguments, a version check and usage option added for posterity.

New Variables and Parsing Ladder

First there are the additions of the program name and version number:

my $PROGRAM = "mntchkd";
my $VERSION = "0.4";

Then, in addition to the new variables a forloop/parsing ladder in perl to figure out what to do with the input:

# Input validation bits
if ((@ARGV <= 0) || (@ARGV >= 7)) {
        print "syntax error\n";
        exit 1;

# Check for usage message first
if ($ARGV[0] eq "usage") {
        exit 0;

for (my $i = 0; $i < @ARGV; $i++) {
    if ($ARGV[$i] =~ /^-version|-V$/) {
        print "$PROGRAM version $VERSION\n";
        exit 1;
    } elsif ($ARGV[$i] eq '-usage') {
        exit 0;
    } elsif ($ARGV[$i] eq '-m') {
        $MNT = $ARGV[++$i];
    } elsif ($ARGV[$i] eq '-l') {
        $LOG = $ARGV[++$i];
    } elsif ($ARGV[$i] eq '-d') {
        $DELAY = $ARGV[++$i];
    } else {
        exit 1;

The code above is pretty simple, the version and usage are checked for first because they invoke an exit. Note that the version did not even require a function.

Next, it is a matter of using the next argument from the input and pre incrementing the loop counter. The options are pretty self explanatory, as each option is chosen the value is assigned. Note that in this version, the mountpoint is a required argument.

Usage Print

The rest of the program actually stays the same as the first version, the only change is the addition of an usage() function:

sub usage {
    print "$PROGRAM [option argument][option argument]...\n";
    print "$PROGRAM [-d delay][-m mountpoint][-l logfile]\n";
    print "Options:\n";
    print "    -d delay     Set check delaytime in seconds to delay\n";
    print "    -m directory Set mountpount to directory\n";
    print "    -l logfile   Send log messages to logfile\n";

Mount Check Complete...

The entire mount check perl daemon can be downloaded from here. Note that there is still some room for improvement in this one. A better parsing loop perhaps, a check to make sure $MNT is specified and others to be sure.

The door for a more generic daemon are left open, however. For all intents, the entire daemonizing process and logging could be written so all the main daemon program does is wait for a 1 or 0 from some check that passes back a message.

Food for thought . .

Next: C Daemon I Previous: Perl Daemon I