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

How do I test whether a file is in use, ie. being written to by a program. Once I know if the file's in use, I can then my program wait before it uses the file.

Replies are listed 'Best First'.
(Ovid -flock) Re: File Use
by Ovid (Cardinal) on Apr 04, 2001 at 23:05 UTC

    The straightforward way to do this is to use flock, but it's "advisory only." There are a couple of basic ways to flock a file (shared, exclusive), but if other programs don't use flock, you're out of luck.

    If your program requests a flock and the file is already exclusively locked, your program knows not to open the file, but again, that doesn't work if the other programs don't bother to use flock. If you can't control the behavior of other programs, perhaps you should examine your requirements and determine an alternative.


    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

      Only my program will be accessing the file. I just need to make sure it's not being used if someone else runs my program. I'm looking at flock now, but can it return true if the file is in use? qball-"I have node idea?!"
        Then you're in luck. You want an exclusive lock on the file:
        use Fcntl ':flock'; # import LOCK_* constants my $filename = "somefile.txt"; open FILE, ">>$filename" or die "Cannot open $filename for writing: $! +"; flock FILE, LOCK_EX or die "Cannot get exclusive lock on $filenam +e: $!";
        Just be sure not to forget to unlock the file when done. Plus, my code above is for appending, which is what I suspect you want.


        Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Re: File Use
by thabenksta (Pilgrim) on Apr 04, 2001 at 23:07 UTC

    If I understand you situation correctly you can take care of this with flock.

    open(HANDLE, ">file.dat"); flock(HANDLE, 2); #lock file # file processing flock(HANDLE, 8); #unlock file close(HANDLE);

    This will lock you file so no one else can write to it while the program is. Any other program will have to wait to write to it.

    Hope that helps.

    my $name = 'Ben Kittrell'; $name=~s/^(.+)\s(.).+$/\L$1$2/g; my $nick = 'tha' . $name . 'sta';
Re: File Use
by qball (Beadle) on Apr 04, 2001 at 23:29 UTC
    Thanks Ovid and thabenksta. Both of your answers are exactly what I need. I appreciate quality feedback.

    qball~"I have node idea?!"