John Doe John Doe - 1 month ago 8
Perl Question

Detecting that files are being copied in a folder

I am running a script which copies one folder from a specific location if it does not exist( or is not consistent). The problems appears when I run concurently the script 2+ times. As the first script is trying to copy the files, the second comes and tryes the same thing resulting in a mess. How could I avoid this situation? Something like system wide mutex.

I tryed a simple test with

-w
, I manually copied the folder and while the folder was copying I run the script:

use strict;
use warnings;

my $filename = 'd:\\folder_to_copy';
if (-w $filename) {
print "i can write to the file\n";
} else {
print "yikes, i can't write to the file!\n";
}


Of course this won't work, cuz I still have write acces to that folder.
Any ideea of how could I check if the folder is being copied in
Perl
or using
batch commands
?

Answer

Sounds like a job for a lock file. There are myriads of CPAN modules that implement lock files, but most of them don't work on Windows. Here are a few that seem to support Windows according to CPAN Testers:

After having a quick view at the source code, the only module I can recommend is File::Flock::Tiny. The others seem racy.

Comments