I'm working on a program that does tasks in tandem. It forks into some number of processes, and the children wait for specifically formatted text files to tell them exactly what to do. Since each text file should only be performed on once, I thought I should get an exclusive file lock on each file before actually doing the work.
But files are sometimes worked on more than once despite the fact that an exclusive lock has returned true. Heres a simplified version of what I'm doing that recreates the error on my computer.
#!/usr/bin/perl
use strict;
use warnings;
use Time::HiRes qw|time sleep|;
use Fcntl qw|:flock|;
mkdir "tmp" or warn $!;
chdir "tmp" or die $!;
for (1 .. 500){
my $pid = fork();
defined($pid) or die "fork failed: $!";
if ($pid == 0) {
child_process();
exit;
}
}
print "DONE FORKING\n";
while (wait() > -1) {}
sub child_process{
while (1){
while (my $file = glob "*.tmp"){
open my $FH, '>', $file or next; #next if unlinked already
if (flock($FH, LOCK_EX | LOCK_NB)){
next unless flock($FH, LOCK_EX | LOCK_NB);
print time(), " YES! I ($$) got a lock on $file!\n";
sleep(.1);
unlink $file;
}
close $FH;
}
sleep(.1);
}
}
Running this, waiting for the "DONE FORKING" message and than typing "touch tmp/random.tmp" produces something like this:
1199321503.71728 YES! I (25930) got a lock on random.tmp!
1199321504.01631 YES! I (25827) got a lock on random.tmp!
1199321504.01702 YES! I (25976) got a lock on random.tmp!
I'm under the impression that there should only be one process that gets an exclusive lock.
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.