nimdokk has asked for the wisdom of the Perl Monks concerning the following question:
I'm running a program out of cron that writes to creates a log file. I need to open it so that I can write direct STDOUT and STDERR to it so that I can capture all the output from the program as it is running. The first thing that happens is that the old log file is removed so I only get data from the current cycle in the log. The problem is that the cron is set to execute every 15 minutes but if an earlier copy of the process is still executing and writing to that log file (and this is a possibility), the new copy will delete that log file. I need to open the log in such a way that the first process is the only process using the file until it is completely done.
Here is an example of the code, probably not the cleanest code, but what will happen is that if I go to a command prompt while the program is sleeping, I can delete the log file before I can close it.
use strict; use Time::localtime; use Fcntl; my $dir="/path/to/bin/perl"; my @perl=(); # Main Program Block MAIN: { sysopen (STDOUT, "$dir/TEST.NEW", O_RDWR | O_CREAT ) or die "Cannot op +en TEST.LOG: $!"; open (STDERR, ">>&STDOUT") or die "Cannot dupe STDOUT to STDERR: $!"; flock(STDOUT, 2) or die "Cannot lock filename: $!"; opendir (DIR, "$dir") or die "Cannot open $dir: $!"; @perl=grep { /\w\.pl/ } readdir DIR; print "@perl\n"; foreach (<@perl>) {print "\$_ is $_\n";} sleep (60); close (STDOUT); close (STDERR); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: File Locking
by perlplexer (Hermit) on Apr 23, 2003 at 15:21 UTC | |
by nimdokk (Vicar) on Apr 23, 2003 at 16:44 UTC | |
by perlplexer (Hermit) on Apr 23, 2003 at 17:55 UTC | |
by nimdokk (Vicar) on Apr 23, 2003 at 18:26 UTC | |
|
Re: File Locking
by zby (Vicar) on Apr 23, 2003 at 15:15 UTC | |
by nimdokk (Vicar) on Apr 23, 2003 at 15:23 UTC | |
by perlplexer (Hermit) on Apr 23, 2003 at 15:31 UTC |