SPUG: Perl Question?

jerry gay jerry.gay at gmail.com
Tue Dec 13 09:48:07 PST 2005


bear with me as i've recently revisited this issue with my own code,
and thought this could be of help.

On 5/11/05, jerry gay <jerry.gay at gmail.com> wrote:
> On 5/11/05, DeRykus, Charles E <charles.e.derykus at boeing.com> wrote:
> > > you might instead consider one of my favorite locking hacks:
> >
> > >  #!/usr/bin/perl
> > >  ...
> > >  ## ensure only one instance of this script is running
> > >  INIT { flock DATA => LOCK_EX | LOCK_NB or exit 1 }
> > >  ...<script body here>...
> > >  __DATA__
> >
> > > which will exit if the script can't get an exclusive lock on itself. no messy lockfiles to worry about. ~jerry
> >
> > Intriguing suggestion but won't this fail on most systems since the DATA
> > filehandle is readonly.... ?
> >
> i'm afraid it's true that it won't work on all systems. which, i
> suppose, is why it's a favorite hack, and not a favorite idiom :)
>
> > See thread below:
> > http://groups-beta.google.com/group/comp.lang.perl.misc/browse_thread/thread/d05e19ca6f8d5e19/8da7e94a9a233bb4?q=flock+__DATA__+group:*perl*&rnum=23&hl=en#8da7e94a9a233bb4
> >
> > Here's the relevant exchange:
> >
> >     John Lin> use Fcntl ':flock';
> >     John Lin>  $| = 1;
> >     John Lin> flock(DATA,LOCK_EX|LOCK_NB) or die "$0 is executing\n";
> >     John Lin> print sleep 1 for 1..10;
> >     John Lin> __DATA__
> >
> >     John Lin> Great!!!  When one program is running, the same program cannot be
> >     John Lin> evoked again.  But no die messages are shown because perl is unable
> >     John Lin> to open the script at all.
> >     ...
> >
> >     Anno Siegel> The problem is again that some systems don't give you an exclusive lock
> >     Anno Siegel> for a file that is only open for reading.
> >
> > Fails on my older Solaris OS for instance.
> >
> i haven't had the pleasure of needing an exclusive lock on a read only
> file when the os doesn't support it, so i probably can't help much
> more at this point. good luck!
>
i have now had the pleasure of experiencing this scenario. not giving
up on my favorite hack (above,) and finding a reference in my notes to
it's source, i found and modified a similar locking example that works
on platforms which don't allow exclusive locks on read-only files.

INIT {
    open ME => '+<', $0 or die "can't lock";
    flock ME => LOCK_EX | LOCK_NB  or exit 1;
}

hope that helps.
~jerry


More information about the spug-list mailing list