I have a question regarding whether a file is currently opened or not (unix). I've written a perl utility which does a directory comparison and picks out any new files that have appeared since it's previous run. I need to check the contents of these new files but only if they are not currently still open by some other process. These files are being written by an Oracle application not by another Perl utility.
I tried using flock but this doesn't seem to work e.g.
while (defined($_ = readdir(AUDDIR))) { next if /^\.\.?$/; unless (delete $files{$_}) { open(FH, "<$_") or die "Can't open file $_: $!\n"; flock(FH, LOCK_EX) or warn "Can't get exclusive lock on file $_ +: $!\n"; close(FH); } }
Notice that in this code I am using exclusive lock mode (even though all I want to do is read the contents). If I use LOCK_SH it grants a shared lock even if the file is currently openned by another process. Using LOCK_EX I get an error
Can't get exclusive lock on file ora_6688.aud : Bad file number
This happens regardless of whether the file is still openned or not.
As it happens in this case the filenames contain the unix pid of the process which wrote (or is still writing) to the file.
I could get a list of all the current pid's and compare it to the list of pid's in the new filenames to see if the filename in question is still open, but this seems a messy way of doing it to me.
Any suggestions on how I can handle this problem would be welcome

In reply to Is file still open ? by Anonymous Monk

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.