in reply to How do I lock a file?

Well, you can use flock():
#!/usr/bin/perl

use strict;
use Fcntl ':flock'; # import LOCK_* constants

open(MYFILE, ">testing");
flock(MYFILE, LOCK_EX);
print "file locked\n"; sleep(100);
flock(MYFILE, LOCK_UN);
print "file unlocked\n";
close MYFILE;
That will lock it as far as other processes that use flock() are concerned. Ie: if you run that, (and it locks and goes to sleep for 100 seconds) and then run another instance of it while the first is sleeping, it will wait for the other to unlock the file. However, if you run one instance of that and "echo lala > testing" it will ignore the lock and just write the file.

I don't know enough to say wether using fcntl() might yeild better results when dealing with other processes that don't try to lock the file before accessing it.

I'd say look at the perldocs on flock() and fcntl() or do some kind of cooperative locking. Ie: touch a lockfile and check it before opening the real file.

Replies are listed 'Best First'.
RE: Answer: How do I lock a file?
by chromatic (Archbishop) on Mar 23, 2000 at 01:54 UTC
    Don't do cooperative locking -- it's not atomic. Suppose you had two processes each contending for a single file. The first file might touch the lock file and then immediately give up control to the second program (hey, it's a race condition and it really happens!). The second program is unable to open the file, even though the first is not using it, because the first has marked the lock file -- or it could try it anyway, grabbing the lock out from underneath it. The behavior is undefined.

    flock is probably your best bet, as it uses the CPU's specific SINGLE operation for obtaining/releasing a lock.