rovf has asked for the wisdom of the Perl Monks concerning the following question:
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):
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:# 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);
- 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>
Ronald Fischer <ynnor@mm.st>
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: locking over the network
by SuicideJunkie (Vicar) on Jan 31, 2011 at 17:07 UTC | |
by rovf (Priest) on Jan 31, 2011 at 17:15 UTC | |
by BrowserUk (Patriarch) on Jan 31, 2011 at 18:24 UTC | |
by tye (Sage) on Jan 31, 2011 at 20:51 UTC | |
by rovf (Priest) on Feb 01, 2011 at 10:11 UTC | |
by Corion (Patriarch) on Feb 01, 2011 at 14:34 UTC | |
| |
by SuicideJunkie (Vicar) on Feb 01, 2011 at 14:28 UTC | |
by tye (Sage) on Feb 01, 2011 at 14:39 UTC | |
| |
Re: locking over the network
by fidesachates (Monk) on Jan 31, 2011 at 19:57 UTC | |
Re: locking over the network
by rowdog (Curate) on Jan 31, 2011 at 20:50 UTC | |
by rovf (Priest) on Feb 01, 2011 at 10:14 UTC | |
by rowdog (Curate) on Feb 02, 2011 at 01:46 UTC | |
by tye (Sage) on Feb 02, 2011 at 03:20 UTC | |
by rowdog (Curate) on Feb 02, 2011 at 17:30 UTC | |
| |
Re: locking over the network
by Anonymous Monk on Jan 31, 2011 at 17:19 UTC | |
by rovf (Priest) on Jan 31, 2011 at 17:33 UTC | |
by tye (Sage) on Feb 02, 2011 at 03:26 UTC | |
by rovf (Priest) on Feb 02, 2011 at 10:27 UTC | |
by tye (Sage) on Feb 02, 2011 at 14:05 UTC | |
|
Back to
Seekers of Perl Wisdom