I have two Perl processes, let's call them A and B. When A runs, it (re)creates a file F (i.e. if F already exists, it will be erased, and then it will be created from scratch). When B runs, it reads the file F (if present).
To coordinate these activities, I would normally use file locking in processes A and B, using a separate lockfile L, like this (error handling omitted):
# Acquire lock
sysopen(LOCKFILE,'L',O_WRONLY|O_CREAT);
while(!flock(LOCKFILE, LOCK_EX|LOCK_NB)) {
sleep(...);
}
# Lock granted!
if(I am process A) {
open(my $file,'<','F');
...
} elsif(I am process B) {
unlink 'F';
open(my $file,'>','F);
...
}
# Release lock
flock(LOCKFILE, LOCK_UN);
close(LOCKFILE);
I think (hope) the basic logic is correct. However, in my case, process A runs on Unix and process B runs on Windows, and the file F needs to be accessed via the network in both cases. From what I have read in, for example,
perlfaq5, locking may or may not work well when done over the network.
Now I have two questions:
- Can this locking algorithm be improved, or is it already "safe enough" for my concrete case?
- Do I really need a separate lockfile L, oder can I lock on file F? Of course I can't then unlink('F'), but if I would truncate the file to length zero after opening it, an unlink wouldn't be necessary.
--
Ronald Fischer <ynnor@mm.st>
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.