openFile gives "file is locked" error on Linux when creating a non-existing file
Viktor Dukhovni
ietf-dane at dukhovni.org
Mon Oct 7 11:04:45 UTC 2024
On Mon, Oct 07, 2024 at 09:52:06PM +1100, Viktor Dukhovni wrote:
> If you need to know whether the file got created by this call, or was
> found to exist already, you need a lower-level API, such as (Unix C):
>
> /* In some cases 0600 is more appropriate */
> int fd = open(path, O_WRONLY|O_CREAT|O_EXCL, 0666);
>
> if (fd >= 0) {
> /* Just created */
> (void) close(fd);
> ...
> } else if (errno == EEXIST) {
> /* Already present */
> ...
> } else {
> /* Permission or other problem */
> ...
> }
I should mention that The above assumes a "local" filesystem, with NFS a
race may still be possible, and the open(2) manpage may describe
work-arounds, e.g. Linux:
On NFS, O_EXCL is supported only when using NFSv3 or later on
kernel 2.6 or later. In NFS environments where O_EXCL support is
not provided, programs that rely on it for performing locking
tasks will contain a race condition. Portable programs that want
to perform atomic file locking using a lockfile, and need to avoid
reliance on NFS support for O_EXCL, can create a unique file on
the same filesystem (e.g., incorporating hostname and PID), and
use link(2) to make a link to the lockfile. If link(2) returns
0, the lock is successful. Otherwise, use stat(2) on the unique
file to check if its link count has increased to 2, in which case
the lock is also successful.
--
Viktor.
More information about the ghc-devs
mailing list