In a current project, I have the need to make sure that a script can only run a single copy at a time. I'd like to hear comments on the sub routine below, which gets called at the beginning of a script. I'm hoping to 'solidify' it enough for reuse in my workplace (across our Unix and Win32 environments).
The latest tweak I've been contemplating is whether calling flock() on PID_FILE would gain me anything. Perhaps preventing a race condition if 2 processes were launched simultaneously?
sub single_instance{
$SIG{INT} = sub {exit()};
my ($prog) = $0 =~ m|(?:.*[/\\])?(.*)$|;
my $tmp_dir = $^O =~ "MSWin32" ? "C:/Windows/Temp" : "/tmp";
my $lockfile = "$tmp_dir/$prog.pid";
local *PID_FILE;
if (-e $lockfile){
open(PID_FILE, "<$lockfile") or die("single_instance(): Can't
+open $lockfile: $!\n");
my $running_pid = <PID_FILE>;
close(PID_FILE);
chomp($running_pid);
if (kill 0, $running_pid){
die("Already running as pid $running_pid\n");
}
}
open(PID_FILE, "+>$lockfile") or die("single_instance(): Can't ope
+n $lockfile: $!\n");
print PID_FILE "$$\n";
close(PID_FILE);
chmod(0666, $lockfile);
eval "END {unlink '$lockfile'}";
die("single_instance(): $@\n") if($@);
}
-Nitrox
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.