in reply to File Use

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.

Cheers,
Ovid

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

Replies are listed 'Best First'.
Re: (Ovid -flock) Re: File Use
by qball (Beadle) on Apr 04, 2001 at 23:07 UTC
    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.

      Cheers,
      Ovid

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