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.
Does Perl have this problem if I use:
open (FILE, "data.txt");
flock (FILE, 2);
Basically, I want to have a cgi that controls an external device and
I want it to read a config file to find the last user (IP) and state
of the device before trying to do anything. And being a cgi, I don't
want race issues.
James
Ken Williams - 03 Feb 2006 03:25 GMT
> 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