in reply to How do I lock a file?
#!/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 |