Hi;

  This seems like a very simple concept, but I'm not getting it, so
I'd like some help.

  So part of this is perl (not understanding readdir and/or glob well
enough) and part of it is not getting the logic right.

  I have five perl scripts.

  I do not want any of them running concurrently as they will use a
common resource which will cause corruption in the resource and will
probably consume too much CPU and/or RAM/ and/or I/O.

  So what I tried was to look in a lock directory if any of the script
names were located in that directory (I tried both glob and readdir,
but I'm tripping up on both of them).

  So if script1.pl starts running, it looks in lock_dir to see if
script[15].pl is a file in lock_dir.

  if it sees any one of them, then it dies (no busywait).

  The script(any of script[1-5].pl) that sees that nothing is in the
lock_dir, then puts itself (touch lock_dir/$0) in the lock_dir and
runs happily to completion, then removes its lock file.

  But where I run into trouble is the actual glob or readdir as $0
might be "./script1.pl" or "/full/path/to/script1.pl" or "script1.pl".
Perhaps I should use basename?  Perhaps a simple regex?

  I tried something similar with glob, but that didn't work well either.

  Here's the concept I tried and it doesn't seem to work right:

#!/usr/bin/perl

use strict;
use warnings;
use English qw( -no_match_vars );

my $cmd;
my $results;
my $lock_dir = $ENV{'HOME'} . "/My_build_lock_dir";
if (-d $lock_dir) {
  opendir my $dh, $lock_dir or die "Cannot open $lock_dir: $!";
  foreach my $file (readdir $dh) {
    next if ($file eq ".");
    next if ($file eq "..");
    die "FATAL ERROR: $file is currently executing, cannot continue
executing $PROGRAM_NAME\n" if ($file eq "script1.pl");
    die "FATAL ERROR: $file is currently executing, cannot continue
executing $PROGRAM_NAME\n" if ($file eq "script2.pl");
    die "FATAL ERROR: $file is currently executing, cannot continue
executing $PROGRAM_NAME\n" if ($file eq "script3.pl");
    die "FATAL ERROR: $file is currently executing, cannot continue
executing $PROGRAM_NAME\n" if ($file eq "script4.pl");
    die "FATAL ERROR: $file is currently executing, cannot continue
executing $PROGRAM_NAME\n" if ($file eq "script5.pl");
  }
  closedir $dh or warn "Unable to close $lock_dir: $!";
} else {
  mkdir $lock_dir;
}
$cmd = "cat $PID > $lock_dir/$PROGRAM_NAME";
$results = qx{$cmd};
print "Added $PROGRAM_NAME to $lock_dir\n";
print "Sleeping for 60 seconds\n";
sleep 60;
unlink "$lock_dir/$PROGRAM_NAME" or die "Failed to remove lock file
($lock_dir/$PROGRAM_NAME); remove manually.\n";
print "Done!\n";

Thanks,
Ken Wolcott

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to