Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: flock question

by Odud (Pilgrim)
on Jun 27, 2000 at 14:32 UTC ( [id://19978]=note: print w/replies, xml ) Need Help??


in reply to flock question

Another one where I post a partial answer to my own question. The problem seems to be that I have made an assumption about how filehandles behave. The code for Copy will open and close the file if given a filename but not if given a filehandle. This makes sense. What surprised me was that closing the file would release the lock. I was thinking that if I had obtained the lock by using filehandle XX then I would have to close it through XX to release the lock. I didn't do an explicit close and was expecting the lock to exist until the end of the script

In summary the sequence of events is:

opened as XX # by me
locked as XX # by me
opened as YY # by copy
closed as YY # by copy and the lock is released

Copy says "Note that passing in files as handles instead of names may lead to loss of information on some operating systems; it is recommended that you use file names whenever possible." - which is how I got into this mess in the first place

Replies are listed 'Best First'.
RE: Re: flock question
by takshaka (Friar) on Jun 28, 2000 at 06:43 UTC
    To work around this, you can lock a semaphore file instead of the actual file you are copying.
    use strict; use File::Copy; use Fcntl ':flock'; # import LOCK_* constants my $status_file = "/tmp/flocktest"; my $semaphore = "/tmp/flocktest.sem"; open(SEM,">$semaphore") || die "Can't open file"; flock(SEM, LOCK_EX) || die "Can't lock file"; copy($status_file,"/tmp/foo"); unlink $semaphore; # only on unix close SEM;
      That's probably the simplest way around it - however when coding I tend to try to minimise the number of "things" that the script has to deal with. In this particular case a number of other files were being used but only one needed the lock and so it seemed logical to keep the lock with the file rather than create another object for the script to manipulate. Perhaps a good idea would be to come up with a generalised set of lock/unlock subroutines that I could use in all my scripts - I'll post it in snippets when I get it written.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://19978]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-25 23:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found