Acapulco has asked for the wisdom of the Perl Monks concerning the following question:
Hello monks,
I've been reading PM for a while but this is my first time asking. Almost always the answer is already there and I just had to search for it... except in this case.
I've been reading about file locking in Perl, as I need to avoid concurrency issues while reading and writing a file.
My general problem is that I have a script that works as a CLI tool, but for certain operations I need to first check the contents of a file and depending on those I either X or Y things. Basically my file contains the state of a part of the system, and if that state is say A I can proceed, but if it's B I can't. The concurrency problem comes from the fact that the CLI can be called multiple times in succession (via scripts, etc) and so they should not have race conditions to check this file. Thus I thought of file locking.
However the issue I have is that everywhere I look I find flock being used but as far as I can tell, obtaining a lock this way is not atomic, since I first need to actually open the file.
Please correct me if I'm wrong, but if I first open then flock, isn't there a non-zero probability that this would cause a race condition?
Is there any way to actually do file locking in an atomic way, so that we open AND flock at the same time (or fail) to avoid this?
I've also looked into semaphores as an alternative, specifically IPC::Semaphores (since these would be shared between processes right?) but I am also forking a few times inside the script and thus the semaphore variable is going to be shared as well, and that would lead me to some difficulties since I would need to make sure the semaphores are not released inadvertently in the incorrect place (by a child for example).
Are my assumptions on flock correct or am I missing something here? if the race condition actually exists, how do people work around that? or do they just ignore it since for most use cases maybe this is a non-issue?
Most CPAN packages are out of the question because I can't really install anything due to policy issues :( and so I was looking for a built-in way to do this.
Thanks a lot for your help! Acapulco
|
|---|