On Feb 2, 2006, at 5:01 PM, James Reynolds wrote:

As I understand it, in C, if I open (create) a file and want to lock it, I should pass in the O_EXLOCK flag at the same time, otherwise, I've got a race condition, another process could potentially lock the file after I've created it, but before I've locked it.

Right.

Does Perl have this problem if I use:

open (FILE, "data.txt");
flock (FILE, 2);

Well, there's no problem if you're just reading, because if you don't get the lock then you just abort (or wait). Only the flock() needs to be atomic by itself, not the open() and the flock() together.

If you need to write too, then you need to acquire an exclusive lock, which I don't know any way to do in perl atomically with the open(). One way to be safe would be to open the file for both reading and writing, try to acquire the exclusive lock, and if you can't, then abort without doing any writing (or wait until you can).

 -Ken

  • flock James Reynolds
    • Re: flock Ken Williams

Reply via email to