How to check if a file is open with Perl?

Given the file name, how can I tell if a file is currently open or in use? (I'm talking about files, not Perl files).

Please note that I am looking for a general-purpose Perl solution, not just for the operating system. At a minimum, I would like something that works on both Windows systems and GNU / Linux.

+6
source share
6 answers

POSIX provides no way to do this. Thus, the portable option is not possible if a portable O / S interface is available.

You need to create a higher level approach that provides a single access point for the start bits. This is similar to lock files.

+3
source

See the following snippet (Linux / Unix only, you don’t tell us which OS you are running):

In one layer:

perl -e 'my $file = $ARGV[0]; print "file $file is opened" if `lsof $file`;' FILE 

In the script:

 #!/usr/bin/env perl -w use strict; my $file = $ARGV[0]; print "file $file is opened\n" if `lsof $file`; 

To run it:

 ./script.pl FILENAME 
+1
source

Try Scalar :: Util

The Scalar :: Util module provides openhandle() for this. Unlike fileno () , it processes perl file descriptors that are not associated with OS file descriptors. Unlike tell () , it does not generate warnings when used in an unopened file descriptor. From the module documentation :

openhandle fh

 Returns FH if FH may be used as a filehandle and is open, or FH is a tied handle. Otherwise "undef" is returned. $fh = openhandle(*STDIN); # \*STDIN $fh = openhandle(\*STDIN); # \*STDIN $fh = openhandle(*NOTOPEN); # undef $fh = openhandle("scalar"); # undef 
0
source

try it

 use strict; open(IN, ">test"); print IN "Hello"; close(IN); if(fileno(IN) == undef ) { print "File is CLOSED\n"; } 
0
source

I know that some time has passed, but for Windows I was lucky that the file is being written trying to lock the file (nothing unusual - just open it for reading, use the internal Perl bundle and close the file). this seems to work even in network files. I'm not sure if this works for Linux (maybe when writing), and I don't know if it can detect other file readers.

0
source

I understand that you do not want to open the file descriptor, but this is probably the simplest IMO method:

 open my $myfh, '<', $my_file or die "Couldn't open $my_file: $!"; 
-1
source

Source: https://habr.com/ru/post/916996/


All Articles