Created
January 4, 2011 16:14
-
-
Save waffle2k/764976 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl -w | |
use strict; | |
use Fcntl qw(:DEFAULT :flock); | |
use constant LOCKFILE => '/tmp/default.lck'; | |
use constant TIMEOUT => 10; | |
my $cmd = shift || die ("You must give a sub command to run\n"); | |
my $timeout = shift || TIMEOUT; | |
my $filename = shift || LOCKFILE; | |
local $SIG{ALRM} = sub { die "Timeout $timeout exceeded\n"; }; | |
alarm $timeout; | |
open FD, "<$filename" | |
or die( "Cannot open $filename: $!\n" ); | |
unless( flock( FD, LOCK_EX | LOCK_NB ) ){ | |
local $| = 1; | |
print "Waiting for lock on filename... ($timeout second timeout)"; | |
flock( FD, LOCK_SH ) or die( "Can't lock file: $!\n" ); | |
print "\n"; | |
} | |
# Received the lock, disable the alarm.. | |
print "Received the lock, disabling the alarm\n"; | |
alarm 0; | |
# Execute the sub command | |
print "Executing: $cmd\n"; | |
unless( system( "$cmd" ) == 0 ){ | |
die( "Couldn't exec $cmd: $!" ); | |
} | |
close( FD ); | |
exit 0; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment