Hi Monks,
I need help with a file locking problem. Basically I have two processes (more than that, actually, but for the sake of explanation, two will do) that are messing with the same file. Some are attempting to read it, some are attempting to write to it. I was under the impression that if everyone uses flock(), things would be just dandy, but that is not the case. Here's what happens:
Process1 comes along and wants to read the file. It does:
open HANDLE, "$file" or die "Can't open: $!";
flock(HANDLE, LOCK_SH); #could use LOCK_EX, it doesn't prevent this p
+roblem
It then starts reading the file. Before Process1 gets done, Process2 comes along and wants to write to the file. Process2 does:
open WRITER, ">$file" or die "Can't open: $!";
flock(WRITER, LOCK_EX);
However, the damage is done before Process2 gets to the flock() call, because when Process2 calls open(), the contents of $file are immediately clobbered (even though Process1 has a flock on it). When Process2 does call flock(), of course, it blocks until Process1 releases his lock before it returns, so nothing gets written to the file until Process1 is done with it.
Is there a good way to ensure that this situation doesn't occur?
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.