How to lock a log file without locking in perl

This is how I do it right now, but it locks the file.

#!/usr/bin/perl use Env qw( $USERNAME ); use File::Tail; use strict; use warnings; my $file = $ARGV[0]; print "$file\n"; my $fileTail = File::Tail->new( name=>$file, maxinterval=>5, tail=>-1); my $line; while ( defined( $line = $fileTail->read ) ) { print $line; } exit; 
+6
windows file locking perl tail
source share
2 answers

According to the documentation, it should not be blocked. What is your operating system? I wonder if you use Windows, although the shebang line does not suggest. Therefore, more detailed information about your environment will be useful.

+4
source share

Windows (or NTFS ... or how Perl implements open on Windows ... not quite sure) has a mandatory lock collapsed into open (). If you open the file for reading, others will not be able to open it for writing. If you open the file for writing, others will not be able to open it for reading or writing.

You keep the file open for reading, so no one can write to the journal. I think what is happening. The file :: Tail probably does not take this into account. It works in general because File :: Tail seems to close and reopen the file descriptor from time to time, if it does not see any activity, it assumes that it has been truncated or recreated. This releases your lock and allows other files to be written.

You can verify this by opening the file for reading with one Perl process, and then try opening it for others to add.

I believe that one way to deal with this is to open the log file using special Windows functions that will allow you to control the lock behavior. Win32 :: SharedFileOpen seems to be something.

 fsopen(my $fh, $file, 'r', SH_DENYNO) or die "Can't read '$file' with no locks: $!\n"; 

This will open the file for reading without locks. Unfortunately, you are responsible for the rest of the work. perlfaq can help.

+4
source share

All Articles