Well, using anything incorrectly can lead to problems, but I still think a simple flock is best - just be careful about it.
> Here you should be able to see the race. Another process
> can get an exclusive lock on the FH during the read open
> (read-only opens don't generally get exclusive locks),
> and between the close of the read and open of the write.
I don't agree with this. First, if another process cannot get
an exclusive lock while *any* other lock is on it. So if
process A locks a file for reading (shared lock) and then
process B tries to get an exclusive lock, process B cannot
get the lock until *all* the locks are gone - shared
and exclusive. In the second case, yes it's a problem, but
that's a bad coding problem, not a problem with flock.
The right way to do it of course is to open the file for
read/write, get an exclusive lock, read in the file, rewind
(usually), write to the file, and close it, releasing the
exclusive lock.
- Proc A open FH for write (using > which clobbers the file contents)
- Proc B opens FH for reading (no lock attempt since it won't likely get an exclusive lock granted)
- Proc A locks FH
- Proc A works with FH
- Proc A closes FH
No need for a semaphore, just change the above a bit:
- Proc A opens FH for read/write (the file is not changed at all yet)
- Proc B opens FH for reading (and gets a shared lock)
- Proc A locks FH exclusively, after B has released it's shared lock
- Proc A works with FH
- Proc A closes FH
And yes, I need to update my tutorial. :)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|