|
Posted by David T. Ashley on 11/30/06 14:49
<veg_all@yahoo.com> wrote in message
news:1164842816.629524.230140@l39g2000cwd.googlegroups.com...
> Thanks for the replies. Here is what I came up with in Perl : Ill
> transfer to php since I need it there as well.
>
> sub check_log_size {
>
> my $size = ( -s 'log' ) / 1024 ;
> $size = int $size;
>
> if ( $size > 25 ) {
> open (FILEHANDLE1, "log" ) || &die_sub ( "Cant open log");
> open (FILEHANDLE2, ">log_old" );
> while (<FILEHANDLE1>) { print FILEHANDLE2 $_; }
> *
> close (FILEHANDLE1);
> *
> close (FILEHANDLE2);
> *
> unlink ( 'log' );
> }
> } # end sub
>
The solution you proposed above probably has race conditions. Specifically,
if a log entry is made (by another process) at the points I've marked with
an asterisk above, you will lose some lines from the log file.
The more traditional solution is just to rename the log file to a new name
(i.e. something like "mv log log_old"). In other words, no copy, just "mv".
Each process that writes the log file has code like this (and I could be
wrong on the exact form, too lazy to look up the 'C' library calls).
handle = fopen("log", "a"); /* Note the "a" for append */
fprintf(handle, "This is my log file entry.\n");
fclose(handle);
The rationale--and somebody please whack me if I'm wrong--is that Unix file
semantics guarantee that when one process(es) opens a file for append and
another process renames it, one process or the other will win. If the "mv"
happens after the "fopen" above but before the "fprintf", then the log entry
will be appended to the renamed file. The next call to fopen in append mode
will create the new current log file (to replace the one that was renamed).
So, when you "mv" a file in order to rotate logs, there will in practice be
a fraction of a second after the rename where some pending log entries will
get written to the renamed file, but none will be lost.
This traces to Unix file semantics, inodes, and all that.
I'm sure Perl has an "mv" function that maps to the operating system's mv
functionality.
Dave.
Navigation:
[Reply to this message]
|