My question is this:

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); }

In reply to File Locking by nimdokk

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.