gnu@perl has asked for the wisdom of the Perl Monks concerning the following question:
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"; ...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Reopening a file handle
by gnu@perl (Pilgrim) on Mar 04, 2003 at 21:41 UTC |