Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a small script that works where it copies a file from one Windows server to another. The destination file is always overwritten. Now I think I should check if the file I am copying from (sourceFile) is opened by someone and also check if the file I am copying to (destinationFile) is being open or being used. Here is my current copy command:
Use File::Copy ... copy($a,$b) || die "$!";
Please advise how I can do this because I am not sure about opening it up and how flock works?
open(INPUT, "<$a"); @data = <INPUT>; close(INPUT); open (OUTPUT, ">$a"); flock(OUTPUT, 2); copy($a,$b) || die "$!";

Replies are listed 'Best First'.
Re: Locking File for copy
by McDarren (Abbot) on Aug 02, 2006 at 02:00 UTC
    One thing you should be aware of, and keep in mind, is that file locking in Perl is advisory only. That is, even if you open a file in locking mode, there is nothing to stop some other script or process from clobbering the file if it isn't observing file locking.

    Programming Perl (aka - The Camel, 3rd Edition) has a very good discussion on File Locking in Chapter 16 (beginning on page 419), with plenty of examples. If you have a copy, then I'd thoroughly recommend reviewing this.

    Failing that, there is always the flock documentation, as well as some discussion on file locking in the DB_File documentation.

    Hope this helps,
    Darren

Re: Locking File for copy
by duff (Parson) on Aug 02, 2006 at 03:21 UTC

    I think you want to use Win32::File to set the file you're reading as read only. Check the rest of the Win32 namespace for how to check the other file. I'm sure there's a module for you in there (caveat emptor, I am not a Windows user if I can help it).