I have a program that when it starts tries to obtain an exclusive lock on a file. In order to do that I have to open the file allowing write. I have done it like this open(FH,"+<./program.pid"); since I can't have the file clobbered.

I now need to request an exclusive lock on that file. If granted, I know that no other instance of this program is running and I can continue. Now I need to read this file, it contains the exit status of the last instance of this program. This lets me know where I need to start up at (I maintain a state file).

After this file is read and I know where to begin in my processing I wish to truncate this file and add the information from this instance of the program. Can I just reopen the file like this open(FH,">./program.pid");? Will this just replace the previous instance of 'FH' or will I be stacking things up?

Also a concern, when I reopen the file with the same filehandle, it is (I think) essentially closing the previous one. This would make me lose my exclusive lock on the file. I could immediately place an exclusive lock again, but this could end up an a race state with another version of this program.

Here's a little example of what I want to do:

... open(PIDFILE,">>$pidFile") or die "Cannot open pidfile, $pidFile: $!\n"; if (! &lock(*PIDFILE) ) { print "\n\tCannot obtain exclusive lock on $pidFile\n", "\tThere must be another instance of this\n", "\tprogram running. Exiting.\n\n"; exit; } # GOT LOCK my @arr = (<PIDFILE>); open(PIDFILE,">$pidFile"); print PIDFILE "$$\n"; ...

In reply to Reopening a file handle by gnu@perl

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.