Article View: news.software.nntp
Article #13062Re: Shlock inside perl scripts?
From: David C Lawrence
Date: Fri, 06 Dec 1996 00:00
Date: Fri, 06 Dec 1996 00:00
60 lines
2477 bytes
2477 bytes
alan@papaioea.manawatu.gen.nz (Alan Brown) writes:
> Has anyone ever written the fragment needed to do shlock inside perl
> scripts, as opposed to making a .sh wrapper for them?
I've used this reliably since I wrote it a few of years ago for perl4.
It isn't my best code, but I haven't cared enough to rewrite it. One
thing that would help with portability would be to include errno.ph
and check the two $! tests against the symbolic constants.
This function purposefully avoids "warn" because I wanted the caller
to report any failure as it deemed necessary.
I think I just spotted a bug with the "$ltmp++" incrementing if $ltmp
already exists. As I recall now, perl will only automagically
increment if the string is all alphanumeric, and if the path passed to
shlock has a "/" in it, then automagic increment won't work --- at
least, not as intended. It will end up creating a file named "1" (or
"2'" or whatever finally doesn't exist).
At any rate, it's been working for me just fine as is.
# &shlock("/path/to/lockfilename") or &shlock("lockfilename")
# get a lock in essentially the same fashion as INN's shlock.
# return 1 on success, 0 for failure.
# originally by tale@uu.net
sub
shlock
{
local($file) = @_;
local($ltmp, $pid);
$ltmp = ($file =~ m%(.*/)%)[0] . "shlock$$";
$ltmp++ while -e $ltmp;
open(LTMP, ">$ltmp") || return 0;
print LTMP "$$\n" || (unlink($ltmp), return 0);
close(LTMP);
if (!link($ltmp, $file)) {
if ($! == 17) { # EEXIST
open(LOCK, "<$file") || (unlink($ltmp), return 0);
$pid = <LOCK>;
(unlink($ltmp), return 0) if (kill(0, $pid) == 1 || $! != 3); # ESRCH
# ok, pid in LOCKfile no longer exists.
close(LOCK);
unlink($file) || (unlink($ltmp), return 0);
link($ltmp, $file) || (unlink($ltmp), return 0);
} else {
unlink($ltmp);
return 0;
}
}
unlink($ltmp);
return 1;
}
Technical Details
Message-ID:
<8iv6fit5n.fsf@rodan.UU.NET>Path:
mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!illumos!news.pugleaf.net!.TX!archive.pugleaf.net!archive.newsdeef.eu!mbox2nntp-news.software.nntp.mbox.zip!not-for-mailReferences:
<5891m7$ndo@papaioea.manawatu.gen.nz>Show Full Headers
Complete Article Headers
Message-ID: <8iv6fit5n.fsf@rodan.UU.NET> Subject: Re: Shlock inside perl scripts? Date: Fri, 06 Dec 1996 00:00:00 +0000 From: David C Lawrence <tale@uunet.uu.net> References: <5891m7$ndo@papaioea.manawatu.gen.nz> Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!illumos!news.pugleaf.net!.TX!archive.pugleaf.net!archive.newsdeef.eu!mbox2nntp-news.software.nntp.mbox.zip!not-for-mail X-Deja-AN: 202693256 Newsgroups: news.software.nntp