I can duplicate your problem. I modified your code like this for testing:
use strict; use File::Copy; use Fcntl ':flock'; # import LOCK_* constants my $status_file = "/tmp/flocktest"; open(STATUS, "+<$status_file") || die "Can't open file"; print "getting lock...\n"; flock(STATUS,LOCK_EX) || die "Can't lock file"; print "waiting...\n"; sleep 10; print "copying file...\n"; # copy(\*STATUS,"/tmp/foo"); copy("$status_file","/tmp/foo"); print "finished copy, waiting....\n"; sleep 10;
With the \*STATUS line uncommented, I get the following behavior (the two columns represent two terminals):
% ./test.pl getting lock... waiting... % ./test.pl getting lock... copying file... finished copy, waiting... % waiting... copying file... finished copy, waiting... %
And with the "$status_file" line uncommented, I get:
% ./test.pl getting lock... waiting... % ./test.pl getting lock... copying file... finished copy, waiting... waiting... copying file... finished copy, waiting... % %
The only explanation I can offer comes from the flock(3B) man page in Solaris:
Locks are on files, not file descriptors. That is, file descriptors duplicated through dup(2) or fork(2) do not result in multiple instances of a lock, but rather multiple references to a single lock. If a process holding a lock on a file forks and the child explicitly unlocks the file, the parent will lose its lock. Locks are not inherited by a child process.
This tells me that when copy() closes the file (even if it opened it using a different handle) the lock is lost. I may be completely wrong, though...

--ZZamboni


In reply to Re: flock question by ZZamboni
in thread flock question by Odud

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.