Hello Monks, I have a situation where I believe I need some sort of atomic action protection for a section of code. I have a small file with a single value in it that is read by my CGI code and then checked for a specific value. If the value is not found then the file is updated to contain the value and a set of code is run and then execution ends. If the value is found then a different set of code is run (the file is not updated at all) and execution ends.
My concern is what will happen if two CGI requests were to hit almost simultaneously so that the code that checks my file for the specific value occurs in the second thread before the first has a chance to update the file which would otherwise cause the second thread to be blocked from running that code.
I came across flock here http://perldoc.perl.org/functions/flock.html
and wondered if this would be the most appropriate solution for my situation or not. From what I read flock may or may not actually lock the file depending on the OS? Is this something I should be concerned with?
Does the following code make sense? Can I read and write after specifying LOCK_SH (or do I have to unlock and then re-lock with LOCK_EX?) Should this work if two processes were to hit my code at the same time?
#Lock my file...
# Use LOCK_SH because I don't want the second thread to be able
# to read until I'm done.
flock( OUTFILE, LOCK_SH);
seek( OUTFILE, 0, 2); # Why do I need this line?
# Read from OUTFILE and if it has the right value then go ahead and
# write the new value into it to indicate that the second process
# should do something different, otherwise you are the second
# process... unlock and do something different.
# Now unlock...
flock( OUTFILE, LOCK_UN);
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:
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
| & || & |
| < || < |
| > || > |
| [ || [ |
| ] || ] ||