Programming Search⌘K

Taskadvanced

Lock a file

Also called file lock, flock, lockf, advisory lock, exclusive lock, shared lock, FileChannel.lock, try_lock.

Take a shared or an exclusive advisory lock on a whole file without a wait, so that programs which use the same lock do not change the file at the same time, and release it when the work is done.

Task

Take a lock on a whole file, so that two programs do not change it at the same time. The task has two functions:

  • try_lock_file(path, mode) opens the file at path, which must exist, and asks for a lock without a wait. mode is shared or exclusive. It returns a lock object, or nothing when another open file has a lock that conflicts. A release of the lock object, or a close of its file, releases the lock.
  • try_lock(path, held, want) is the entry of the cases. It takes the lock held (none, shared or exclusive) with one open of the file, then calls try_lock_file(path, want) with a second open. It returns true when the second call got the lock.

The rules of the two modes are the rules of flock. Linux says of a shared lock: "More than one process may hold a shared lock for a given file at a given time." Of an exclusive lock: "Only one process may hold an exclusive lock for a given file at a given time." And: "A single file may not simultaneously have both shared and exclusive locks." So a reader takes a shared lock, and a writer takes an exclusive lock.

The locks are advisory. They stop only the programs that ask for the same lock. Linux says: "flock () places advisory locks only; given suitable permissions on a file, a process is free to ignore the use of flock () and perform I/O on the file."

Report an error when the file does not exist, and do not make it. JavaScript and TypeScript are not in the solutions, because Node.js has no call that locks a file (see Pitfalls). SQL, regular expressions, HTML and CSS do not apply, because they do not open files.

Solutions

  • Python. fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB), or LOCK_SH for a shared lock. A lock that is busy raises BlockingIOError. Python says: "If the flock() call fails, an OSError exception is raised." The solution opens the file again for each lock, with os.open(path, os.O_RDWR), because a flock lock belongs to the open file.
  • Java. FileChannel.tryLock(0, Long.MAX_VALUE, shared). Java says: "If it fails to acquire a lock because an overlapping lock is held by another program then it returns null ." But "File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine." A second lock in the same JVM throws OverlappingFileLockException, and the solution gives null for it too. So the Java tests take the first lock in a child JVM.
  • C#. .NET has no call that locks a whole file. The FileShare argument of FileStream does it: FileShare.None "Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed." On Unix, .NET enforces FileShare with advisory locks: the .NET 11 notes say that on iOS and tvOS "FileShare restrictions are no longer enforced by those locks", and that "Mac Catalyst and other platforms keep their existing defaults". The solution opens with FileShare.None for an exclusive lock, and with read access and FileShare.ReadWrite for a shared lock. A lock that is busy gives an IOException.
  • Go. The os package has no lock call. The solution calls syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB), and a lock that is busy gives syscall.EWOULDBLOCK. The file has the build constraint unix.
  • Rust. File::try_lock and File::try_lock_shared, in the standard library. try_lock "Returns Err(TryLockError::WouldBlock) if a different lock is already held on this file (via another handle/descriptor)." On Unix, it "currently corresponds to the flock function on Unix with the LOCK_EX flag". A drop of the File releases the lock.
  • C. open(path, O_RDWR), then flock(fd, LOCK_EX | LOCK_NB). flock is not in POSIX, but Linux, macOS and the BSDs have it. A lock that is busy gives -1 with errno set to EWOULDBLOCK.
  • C++. The C++ library has no file lock. The solution calls open and flock as in C, and puts the descriptor in a class whose destructor releases the lock, so an exception does not leave the lock in place.
  • Bash. The flock command of util-linux "manages flock(2) locks from within shell scripts or from the command line". The solution opens the file on a new descriptor with exec {fd}<"$path", then runs flock --nonblock --exclusive "$fd". Linux has the command, and macOS does not have it by default, so the test skips when it is not installed. A read-only descriptor is sufficient: "A shared or exclusive lock can be placed on a file regardless of the mode in which the file was opened."

In Python, a second open of the file gets no lock while the first open holds it, and gets it after the release:

import fcntl
import os
import tempfile

os.chdir(tempfile.mkdtemp())
with open("data.txt", "w", encoding="utf-8") as f:
    f.write("alpha\n")


def try_lock_file(path, op):
    fd = os.open(path, os.O_RDWR)
    try:
        fcntl.flock(fd, op | fcntl.LOCK_NB)
    except BlockingIOError:
        os.close(fd)
        return None
    return fd


first = try_lock_file("data.txt", fcntl.LOCK_EX)
print("first open, exclusive:", first is not None)
print("second open, shared:", try_lock_file("data.txt", fcntl.LOCK_SH) is not None)
os.close(first)  # the close releases the lock
second = try_lock_file("data.txt", fcntl.LOCK_SH)
print("after the release, shared:", second is not None)
os.close(second)
Output
first open, exclusive: True
second open, shared: False
after the release, shared: True

In Go, with syscall.Flock:

package main

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"syscall"
)

func tryLock(path string, how int) (*os.File, error) {
	f, err := os.OpenFile(path, os.O_RDWR, 0)
	if err != nil {
		return nil, err
	}
	if err := syscall.Flock(int(f.Fd()), how|syscall.LOCK_NB); err != nil {
		f.Close()
		if errors.Is(err, syscall.EWOULDBLOCK) {
			return nil, nil
		}
		return nil, err
	}
	return f, nil
}

func main() {
	dir, err := os.MkdirTemp("", "lock-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "data.txt")
	if err := os.WriteFile(path, []byte("alpha\n"), 0o644); err != nil {
		panic(err)
	}
	a, _ := tryLock(path, syscall.LOCK_SH)
	b, _ := tryLock(path, syscall.LOCK_SH)
	c, _ := tryLock(path, syscall.LOCK_EX)
	fmt.Println("two shared locks:", a != nil && b != nil)
	fmt.Println("exclusive lock while they are held:", c != nil)
	a.Close()
	b.Close()
	_, err = tryLock(filepath.Join(dir, "missing.txt"), syscall.LOCK_EX)
	fmt.Println("missing file is an error:", errors.Is(err, os.ErrNotExist))
}
Output
two shared locks: true
exclusive lock while they are held: false
missing file is an error: true

Edge cases

The cases are in cases/basic.jsonl, cases/edge.jsonl and cases/errors.jsonl. Each test runs in a new directory that holds the file data.txt with the text alpha.

  • no-lock-exclusive and no-lock-shared: with no other lock, each mode is given.
  • exclusive-with-exclusive: the second exclusive lock is not given, and the call does not wait.
  • shared-with-shared: two shared locks are given together.
  • shared-with-exclusive and exclusive-with-shared: a shared lock and an exclusive lock are not given together.
  • Errors: missing.txt gives not-found, and the call does not make the file.

In each case, the content of the file stays alpha. The native tests also check that a release or a close frees the lock, so that a new call gets it, and the Python, C and C++ tests check that a child process sees the lock too.

Pitfalls

  • fcntl and lockf locks belong to the process. POSIX record locks (fcntl with F_SETLK, and lockf) are not the same as flock. Linux says: "If a process closes any file descriptor referring to a file, then all of the process's locks on that file are released, regardless of the file descriptor(s) on which the locks were obtained." SQLite, which uses these locks, says that "the close() system call will cancel all POSIX advisory locks on the same file for all threads and all file descriptors in the process." In this example, a read of the file by another part of the program drops the lock:

This code runs but gives a wrong answer on purpose.

import fcntl
import os
import tempfile

os.chdir(tempfile.mkdtemp())
with open("data.txt", "w", encoding="utf-8") as f:
    f.write("alpha\n")

fd = os.open("data.txt", os.O_RDWR)
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
with open("data.txt", encoding="utf-8") as other:  # a library reads the file
    other.read()

pid = os.fork()
if pid == 0:
    try:
        fcntl.lockf(os.open("data.txt", os.O_RDWR), fcntl.LOCK_EX | fcntl.LOCK_NB)
        print("another process got the lock", flush=True)
    except OSError:
        print("another process must wait", flush=True)
    os._exit(0)
os.waitpid(pid, 0)
Output
another process got the lock

Also, "The threads in a process share locks." Linux has open file description locks (F_OFD_SETLK), which belong to the open file as flock locks do, but they are Linux-specific.

  • Java locks do not stop the threads of the same JVM. Use a lock in memory for the threads of the program, and the file lock for other programs.
  • An advisory lock does not stop a program that does not ask for it. A text editor or a cp can still change the file. Use the lock only among programs that you control, and give each the same rule.
  • Node.js has no file lock. The usual way is a lock file: make data.txt.lock with the flag "wx", which fails when the file exists, and remove it after the work. A program that stops before the remove leaves the lock file, so the lock file must hold the process ID or a time, and the next program must check it. See Create a temporary file for the "wx" flag.
  • NFS and other network file systems. Linux says that newer NFS clients "support flock () locks by emulating them as fcntl(2) byte-range locks on the entire file. This means that fcntl(2) and flock () locks do interact with one another over NFS. It also means that in order to place an exclusive lock, the file must be opened for writing." The solutions open the file for reading and writing for this reason, except for the shared locks of C# and Bash.
  • A change of mode is not atomic. A program that holds a shared lock and asks for an exclusive lock does not keep the shared lock between the two. Linux says: "the existing lock is first removed, and then a new lock is established." Release the lock, take the exclusive lock, and read the file again.
  • Lock the file, not the name. When a writer replaces the file with a rename, as in Write a file atomically, the lock stays on the old file, and a new reader opens the new file with no lock. Lock a separate file that never changes, for example data.txt.lock, and keep it.

Code

The build runs the native tests of each language in a pinned toolchain.

lock_file.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/lock-a-file/.

import fcntl
import os


class FileLock:
    """An flock lock on a whole file. Release it, or use it in a with statement."""

    def __init__(self, fd: int) -> None:
        self._fd = fd

    def release(self) -> None:
        if self._fd >= 0:
            fcntl.flock(self._fd, fcntl.LOCK_UN)
            os.close(self._fd)  # the close also releases the lock
            self._fd = -1

    def __enter__(self) -> "FileLock":
        return self

    def __exit__(self, *exc: object) -> None:
        self.release()


def try_lock_file(path: str | os.PathLike[str], mode: str) -> FileLock | None:
    """Ask for a shared or an exclusive lock on path, without a wait.

    It returns None when another open file has a lock that conflicts.
    """
    op = {"shared": fcntl.LOCK_SH, "exclusive": fcntl.LOCK_EX}[mode]
    # flock locks belong to the open file, so each call opens the file again.
    # The file must exist: O_CREAT is not given.
    fd = os.open(path, os.O_RDWR)
    try:
        fcntl.flock(fd, op | fcntl.LOCK_NB)
    except BlockingIOError:
        os.close(fd)
        return None
    except BaseException:
        os.close(fd)
        raise
    return FileLock(fd)


def try_lock(path: str | os.PathLike[str], held: str, want: str) -> bool:
    """The entry of the cases: take held, then ask for want."""
    first = None if held == "none" else try_lock_file(path, held)
    try:
        second = try_lock_file(path, want)
        if second is None:
            return False
        second.release()
        return True
    finally:
        if first is not None:
            first.release()
test_lock_file.py 67 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/lock-a-file/.

import os
from pathlib import Path

import pytest

from lock_file import try_lock, try_lock_file

CASES = {
    "no-lock-exclusive": ("none", "exclusive", True),
    "no-lock-shared": ("none", "shared", True),
    "exclusive-with-exclusive": ("exclusive", "exclusive", False),
    "shared-with-shared": ("shared", "shared", True),
    "shared-with-exclusive": ("shared", "exclusive", False),
    "exclusive-with-shared": ("exclusive", "shared", False),
}


@pytest.fixture
def data(tmp_path: Path) -> Path:
    path = tmp_path / "data.txt"
    path.write_text("alpha\n")
    return path


@pytest.mark.parametrize("name", CASES)
def test_cases(data: Path, name: str) -> None:
    held, want, expect = CASES[name]
    assert try_lock(data, held, want) is expect
    assert data.read_text() == "alpha\n"


def test_release_frees_the_lock(data: Path) -> None:
    lock = try_lock_file(data, "exclusive")
    assert lock is not None
    assert try_lock_file(data, "exclusive") is None
    lock.release()
    again = try_lock_file(data, "exclusive")
    assert again is not None
    again.release()


def test_with_statement_frees_the_lock(data: Path) -> None:
    with try_lock_file(data, "exclusive") as lock:
        assert lock is not None
        assert try_lock_file(data, "shared") is None
    with try_lock_file(data, "shared") as again:
        assert again is not None


def test_child_process_sees_the_lock(data: Path) -> None:
    lock = try_lock_file(data, "exclusive")
    assert lock is not None
    pid = os.fork()
    if pid == 0:
        os._exit(0 if try_lock_file(data, "shared") is None else 1)
    _, status = os.waitpid(pid, 0)
    lock.release()
    assert os.waitstatus_to_exitcode(status) == 0


def test_missing_file(tmp_path: Path) -> None:
    with pytest.raises(FileNotFoundError):
        try_lock_file(tmp_path / "missing.txt", "exclusive")
    assert os.listdir(tmp_path) == []
lock_file.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/lock-a-file/.

#include "lock_file.hpp"

#include <fcntl.h>
#include <sys/file.h>
#include <unistd.h>

#include <cerrno>

namespace files {

FileLock& FileLock::operator=(FileLock&& other) noexcept {
    if (this != &other) {
        release();
        fd_ = other.fd_;
        other.fd_ = -1;
    }
    return *this;
}

void FileLock::release() noexcept {
    if (fd_ >= 0) {
        ::flock(fd_, LOCK_UN);
        ::close(fd_);  // the close also releases the lock
        fd_ = -1;
    }
}

std::optional<FileLock> try_lock_file(const std::filesystem::path& path, LockMode mode, std::error_code& ec) {
    ec.clear();
    if (mode == LockMode::none) {
        ec = std::make_error_code(std::errc::invalid_argument);
        return std::nullopt;
    }
    // flock locks belong to the open file, so each call opens the file again.
    int fd = ::open(path.c_str(), O_RDWR);
    if (fd < 0) {
        ec = {errno, std::generic_category()};
        return std::nullopt;
    }
    int op = mode == LockMode::shared ? LOCK_SH : LOCK_EX;
    while (::flock(fd, op | LOCK_NB) != 0) {
        if (errno == EINTR) continue;
        int e = errno;
        ::close(fd);
        if (e != EWOULDBLOCK) ec = {e, std::generic_category()};
        return std::nullopt;
    }
    return FileLock(fd);
}

bool try_lock(const std::filesystem::path& path, LockMode held, LockMode want, std::error_code& ec) {
    std::optional<FileLock> first;
    if (held != LockMode::none) {
        first = try_lock_file(path, held, ec);
        if (ec) return false;
    }
    return try_lock_file(path, want, ec).has_value();
}

}  // namespace files
lock_file.hpp 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/lock-a-file/.

#pragma once

#include <filesystem>
#include <optional>
#include <system_error>

namespace files {

enum class LockMode { none, shared, exclusive };

// An flock lock on a whole file. The destructor releases the lock and closes
// the file, so the lock cannot stay after an exception.
class FileLock {
public:
    explicit FileLock(int fd) : fd_(fd) {}
    FileLock(FileLock&& other) noexcept : fd_(other.fd_) { other.fd_ = -1; }
    FileLock& operator=(FileLock&& other) noexcept;
    FileLock(const FileLock&) = delete;
    FileLock& operator=(const FileLock&) = delete;
    ~FileLock() { release(); }

    // Releases the lock and closes the file. A second call does nothing.
    void release() noexcept;

private:
    int fd_;
};

// Asks for a shared or an exclusive lock on path, which must exist, without a
// wait. The C++ library has no file lock, so this calls POSIX open and flock.
// It returns no value and no error when another open file has a lock that
// conflicts. On an error it sets ec and returns no value.
std::optional<FileLock> try_lock_file(const std::filesystem::path& path, LockMode mode, std::error_code& ec);

// The entry of the cases: takes held, then asks for want.
bool try_lock(const std::filesystem::path& path, LockMode held, LockMode want, std::error_code& ec);

}  // namespace files
test_lock_file.cpp 81 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/lock-a-file/.

#include <sys/wait.h>
#include <unistd.h>

#include <cstdio>
#include <filesystem>
#include <fstream>
#include <string>
#include <system_error>

#include "lock_file.hpp"

namespace fs = std::filesystem;
using files::LockMode;

namespace {

const fs::path dir = "lock_tree";
const fs::path path = dir / "data.txt";
int failures = 0;

void expect(bool ok, const std::string& what) {
    if (!ok) {
        std::fprintf(stderr, "%s\n", what.c_str());
        ++failures;
    }
}

void fresh() {
    fs::remove_all(dir);
    fs::create_directories(dir);
    std::ofstream(path) << "alpha\n";
}

}  // namespace

int main() {
    struct Case {
        const char* name;
        LockMode held, want;
        bool expect;
    };
    const Case cases[] = {
        {"no-lock-exclusive", LockMode::none, LockMode::exclusive, true},
        {"no-lock-shared", LockMode::none, LockMode::shared, true},
        {"exclusive-with-exclusive", LockMode::exclusive, LockMode::exclusive, false},
        {"shared-with-shared", LockMode::shared, LockMode::shared, true},
        {"shared-with-exclusive", LockMode::shared, LockMode::exclusive, false},
        {"exclusive-with-shared", LockMode::exclusive, LockMode::shared, false},
    };
    std::error_code ec;
    for (const Case& c : cases) {
        fresh();
        bool got = files::try_lock(path, c.held, c.want, ec);
        expect(!ec && got == c.expect, c.name);
    }

    fresh();
    {
        auto a = files::try_lock_file(path, LockMode::exclusive, ec);
        expect(a.has_value(), "first lock");
        expect(!files::try_lock_file(path, LockMode::exclusive, ec) && !ec, "second lock is busy");
        pid_t pid = fork();
        if (pid == 0) _exit(files::try_lock_file(path, LockMode::shared, ec) ? 1 : 0);
        int status = 0;
        waitpid(pid, &status, 0);
        expect(WIFEXITED(status) && WEXITSTATUS(status) == 0, "child process sees the lock");
    }
    // The destructor of a released the lock.
    expect(files::try_lock_file(path, LockMode::exclusive, ec).has_value(), "lock after the destructor");

    files::try_lock_file(dir / "missing.txt", LockMode::exclusive, ec);
    expect(ec == std::errc::no_such_file_or_directory && !fs::exists(dir / "missing.txt"), "missing-file");

    fs::remove_all(dir);
    if (failures != 0) return 1;
    std::printf("ok\n");
    return 0;
}
LockFile.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/lock-a-file/.

import static java.nio.file.StandardOpenOption.READ;
import static java.nio.file.StandardOpenOption.WRITE;

import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Path;

/**
 * Takes advisory locks on files with FileChannel.tryLock. A Java lock belongs to the whole
 * virtual machine: two locks of one JVM on one file do not wait for each other, and the second
 * tryLock throws OverlappingFileLockException. So the locks keep other programs out, not other
 * threads of this program.
 */
public final class LockFile {
  private LockFile() {}

  /**
   * Asks for a shared or an exclusive lock on the whole file, without a wait. It returns null
   * when another program, or this JVM, has a lock that conflicts. Close the lock to release it
   * and its channel. The file must exist.
   */
  public static FileLock tryLockFile(Path path, boolean shared) throws IOException {
    // A shared lock needs a channel open for reading, and an exclusive lock needs one open for
    // writing, so the channel is open for both. Without CREATE, a missing file is an error.
    FileChannel ch = FileChannel.open(path, READ, WRITE);
    try {
      FileLock lock = ch.tryLock(0, Long.MAX_VALUE, shared);
      if (lock == null) {
        ch.close();
      }
      return lock;
    } catch (OverlappingFileLockException e) {
      ch.close();
      return null;
    } catch (IOException | RuntimeException e) {
      ch.close();
      throw e;
    }
  }

  /** Releases a lock from tryLockFile and closes its channel. */
  public static void release(FileLock lock) throws IOException {
    FileChannel ch = lock.channel();
    try {
      lock.release();
    } finally {
      ch.close();
    }
  }

  /**
   * The holder of the tests: "java LockFile hold PATH MODE" takes the lock, prints "locked",
   * and keeps the lock until its standard input ends.
   */
  public static void main(String[] args) throws IOException {
    if (args.length != 3 || !args[0].equals("hold")) {
      System.err.println("usage: LockFile hold PATH shared|exclusive");
      System.exit(2);
    }
    FileLock lock = tryLockFile(Path.of(args[1]), args[2].equals("shared"));
    System.out.println(lock == null ? "busy" : "locked");
    System.out.flush();
    while (System.in.read() >= 0) {
      // Wait for the end of the input.
    }
    if (lock != null) {
      release(lock);
    }
  }
}
LockFileTest.java 111 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/lock-a-file/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class LockFileTest {
  @TempDir Path dir;

  private Path data() throws IOException {
    Path path = dir.resolve("data.txt");
    Files.writeString(path, "alpha\n");
    return path;
  }

  /** Java locks belong to the JVM, so the held lock is in a child JVM. */
  private static Process hold(Path path, String mode) throws Exception {
    String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
    // The directory or jar that holds LockFile.class, for the class path of the child.
    String classes =
        Path.of(LockFile.class.getProtectionDomain().getCodeSource().getLocation().toURI())
            .toString();
    Process p =
        new ProcessBuilder(java, "-cp", classes, "LockFile", "hold", path.toString(), mode)
            .redirectError(ProcessBuilder.Redirect.INHERIT)
            .start();
    BufferedReader out =
        new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8));
    assertEquals("locked", out.readLine());
    return p;
  }

  private static void stop(Process p) throws Exception {
    p.getOutputStream().close();
    p.waitFor(30, TimeUnit.SECONDS);
  }

  @ParameterizedTest(name = "{0}")
  @CsvSource({
    "no-lock-exclusive, none, exclusive, true",
    "no-lock-shared, none, shared, true",
    "exclusive-with-exclusive, exclusive, exclusive, false",
    "shared-with-shared, shared, shared, true",
    "shared-with-exclusive, shared, exclusive, false",
    "exclusive-with-shared, exclusive, shared, false",
  })
  void tryLock(String name, String held, String want, boolean expect) throws Exception {
    Path path = data();
    Process holder = held.equals("none") ? null : hold(path, held);
    try {
      FileLock lock = LockFile.tryLockFile(path, want.equals("shared"));
      assertEquals(expect, lock != null, name);
      if (lock != null) {
        LockFile.release(lock);
      }
    } finally {
      if (holder != null) {
        stop(holder);
      }
    }
    assertEquals("alpha\n", Files.readString(path));
  }

  @Test
  void releaseFreesTheLock() throws Exception {
    Path path = data();
    FileLock lock = LockFile.tryLockFile(path, false);
    assertNotNull(lock);
    LockFile.release(lock);
    Process holder = hold(path, "exclusive");
    try {
      assertNull(LockFile.tryLockFile(path, false));
    } finally {
      stop(holder);
    }
    FileLock again = LockFile.tryLockFile(path, false);
    assertNotNull(again);
    LockFile.release(again);
  }

  @Test
  void sameJvmGivesNull() throws IOException {
    Path path = data();
    FileLock first = LockFile.tryLockFile(path, true);
    assertNotNull(first);
    // Two shared locks of one JVM overlap, so the second call gets no lock.
    assertNull(LockFile.tryLockFile(path, true));
    LockFile.release(first);
  }

  @Test
  void missingFile() {
    assertThrows(NoSuchFileException.class, () -> LockFile.tryLockFile(dir.resolve("missing.txt"), false));
  }
}
lock_file.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/lock-a-file/.

// flock is not in POSIX, but Linux and the BSDs (with macOS) have it.
#define _DEFAULT_SOURCE
#define _DARWIN_C_SOURCE

#include "lock_file.h"

#include <errno.h>
#include <fcntl.h>
#include <sys/file.h>
#include <unistd.h>

int try_lock_file(const char *path, enum lock_mode mode) {
    if (mode != LOCK_MODE_SHARED && mode != LOCK_MODE_EXCLUSIVE) {
        errno = EINVAL;
        return -1;
    }
    // flock locks belong to the open file, so each call opens the file again.
    // Without O_CREAT, a missing file is an error.
    int fd = open(path, O_RDWR);
    if (fd < 0) return -1;
    int op = mode == LOCK_MODE_SHARED ? LOCK_SH : LOCK_EX;
    while (flock(fd, op | LOCK_NB) != 0) {
        if (errno == EINTR) continue;
        int e = errno;
        close(fd);
        errno = e;
        return -1;
    }
    return fd;
}

int unlock_file(int fd) {
    int rc = flock(fd, LOCK_UN);
    int e = errno;
    // The close also releases the lock, so the close runs after an error too.
    if (close(fd) != 0 && rc == 0) return -1;
    errno = e;
    return rc;
}

int try_lock(const char *path, enum lock_mode held, enum lock_mode want) {
    int first = -1;
    if (held != LOCK_MODE_NONE && (first = try_lock_file(path, held)) < 0) return -1;
    int result;
    int second = try_lock_file(path, want);
    if (second >= 0) {
        result = unlock_file(second) == 0 ? 1 : -1;
    } else {
        result = errno == EWOULDBLOCK ? 0 : -1;
    }
    int e = errno;
    if (first >= 0) unlock_file(first);
    errno = e;
    return result;
}
lock_file.h 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/lock-a-file/.

#ifndef LOCK_FILE_H
#define LOCK_FILE_H

enum lock_mode { LOCK_MODE_NONE, LOCK_MODE_SHARED, LOCK_MODE_EXCLUSIVE };

// Opens path, which must exist, and asks for a shared or an exclusive flock
// lock on it, without a wait. It returns the descriptor that holds the lock.
// It returns -1 with errno EWOULDBLOCK when another open file has a lock that
// conflicts, and -1 with another errno on an error.
int try_lock_file(const char *path, enum lock_mode mode);

// Releases the lock of fd and closes fd. It returns 0, or -1 with errno set.
int unlock_file(int fd);

// The entry of the cases: takes held, then asks for want. It returns 1 when
// the second lock was given, 0 when it was not, and -1 with errno on an error.
int try_lock(const char *path, enum lock_mode held, enum lock_mode want);

#endif
test_lock_file.c 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/lock-a-file/.

#define _POSIX_C_SOURCE 200809L

#include "lock_file.h"

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>

static const char *path = "lock_tree/data.txt";
static int failures = 0;

static void expect(int ok, const char *what) {
    if (!ok) {
        fprintf(stderr, "%s\n", what);
        failures++;
    }
}

static void fresh(void) {
    if (system("rm -rf lock_tree && mkdir lock_tree && printf 'alpha\\n' > lock_tree/data.txt") != 0) exit(2);
}

int main(void) {
    static const struct {
        const char *name;
        enum lock_mode held, want;
        int expect;
    } cases[] = {
        {"no-lock-exclusive", LOCK_MODE_NONE, LOCK_MODE_EXCLUSIVE, 1},
        {"no-lock-shared", LOCK_MODE_NONE, LOCK_MODE_SHARED, 1},
        {"exclusive-with-exclusive", LOCK_MODE_EXCLUSIVE, LOCK_MODE_EXCLUSIVE, 0},
        {"shared-with-shared", LOCK_MODE_SHARED, LOCK_MODE_SHARED, 1},
        {"shared-with-exclusive", LOCK_MODE_SHARED, LOCK_MODE_EXCLUSIVE, 0},
        {"exclusive-with-shared", LOCK_MODE_EXCLUSIVE, LOCK_MODE_SHARED, 0},
    };
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        fresh();
        expect(try_lock(path, cases[i].held, cases[i].want) == cases[i].expect, cases[i].name);
    }

    // A release frees the lock.
    fresh();
    int a = try_lock_file(path, LOCK_MODE_EXCLUSIVE);
    expect(a >= 0, "first lock");
    errno = 0;
    expect(try_lock_file(path, LOCK_MODE_EXCLUSIVE) == -1 && errno == EWOULDBLOCK, "second lock is busy");
    expect(unlock_file(a) == 0, "unlock");
    int b = try_lock_file(path, LOCK_MODE_EXCLUSIVE);
    expect(b >= 0, "lock after the unlock");

    // A child process sees the lock.
    pid_t pid = fork();
    if (pid == 0) _exit(try_lock_file(path, LOCK_MODE_SHARED) == -1 && errno == EWOULDBLOCK ? 0 : 1);
    int status = 0;
    waitpid(pid, &status, 0);
    expect(WIFEXITED(status) && WEXITSTATUS(status) == 0, "child process sees the lock");
    unlock_file(b);

    errno = 0;
    expect(try_lock_file("lock_tree/missing.txt", LOCK_MODE_EXCLUSIVE) == -1 && errno == ENOENT, "missing-file");
    struct stat st;
    expect(stat("lock_tree/missing.txt", &st) != 0, "missing-file: no file is made");

    if (system("rm -rf lock_tree") != 0) return 2;
    if (failures == 0) printf("all tests pass\n");
    return failures == 0 ? 0 : 1;
}
LockFile.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/lock-a-file/.

using System.Runtime.Versioning;

// .NET has no lock call for a whole file. The FileShare argument of a
// FileStream does the job: on Unix, .NET enforces FileShare with advisory
// locks on the whole file. FileShare.None asks for an exclusive lock, and read
// access with FileShare.ReadWrite asks for a shared lock. When another open
// file has a lock that conflicts, the constructor throws an IOException. The
// tests check this. FileStream.Lock locks only a byte range.
[UnsupportedOSPlatform("windows")]
public static class LockFile
{
    // Asks for a shared or an exclusive lock on path, without a wait. It
    // returns null when another open file has a lock that conflicts. Dispose
    // the stream to release the lock. The file must exist.
    public static FileStream? TryLockFile(string path, bool exclusive)
    {
        if (!File.Exists(path))
        {
            // FileMode.Open gives the error, but the check makes it clear.
            throw new FileNotFoundException("no such file", path);
        }
        try
        {
            return exclusive
                ? new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
                : new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        }
        catch (IOException e) when (e is not FileNotFoundException and not DirectoryNotFoundException)
        {
            return null;
        }
    }

    // The entry of the cases: takes held ("none", "shared" or "exclusive"),
    // then asks for want.
    public static bool TryLock(string path, string held, string want)
    {
        using FileStream? first = held == "none" ? null : TryLockFile(path, held == "exclusive");
        using FileStream? second = TryLockFile(path, want == "exclusive");
        return second != null;
    }
}
LockFileTests.cs 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/lock-a-file/.

using System.Runtime.Versioning;
using Xunit;

[UnsupportedOSPlatform("windows")]
public sealed class LockFileTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("lock-file-").FullName;

    private string Data => Path.Combine(dir, "data.txt");

    public LockFileTests() => File.WriteAllText(Data, "alpha\n");

    public void Dispose() => Directory.Delete(dir, recursive: true);

    [Theory]
    [InlineData("no-lock-exclusive", "none", "exclusive", true)]
    [InlineData("no-lock-shared", "none", "shared", true)]
    [InlineData("exclusive-with-exclusive", "exclusive", "exclusive", false)]
    [InlineData("shared-with-shared", "shared", "shared", true)]
    [InlineData("shared-with-exclusive", "shared", "exclusive", false)]
    [InlineData("exclusive-with-shared", "exclusive", "shared", false)]
    public void TryLock(string name, string held, string want, bool expect)
    {
        Assert.Equal(expect, LockFile.TryLock(Data, held, want));
        Assert.Equal("alpha\n", File.ReadAllText(Data));
        Assert.True(name.Length > 0);
    }

    [Fact]
    public void DisposeFreesTheLock()
    {
        FileStream? first = LockFile.TryLockFile(Data, exclusive: true);
        Assert.NotNull(first);
        Assert.Null(LockFile.TryLockFile(Data, exclusive: true));
        first.Dispose();
        using FileStream? again = LockFile.TryLockFile(Data, exclusive: true);
        Assert.NotNull(again);
    }

    [Fact]
    public void MissingFile()
    {
        Assert.Throws<FileNotFoundException>(() => LockFile.TryLockFile(Path.Combine(dir, "missing.txt"), exclusive: true));
        Assert.False(File.Exists(Path.Combine(dir, "missing.txt")));
    }
}
lock_file.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/lock-a-file/.

//go:build unix

// Package lockfile takes flock locks on files. The os package has no lock
// call, so it calls syscall.Flock.
package lockfile

import (
	"errors"
	"fmt"
	"os"
	"syscall"
)

// Lock is an flock lock on a whole file.
type Lock struct{ f *os.File }

// Release removes the lock and closes the file.
func (l *Lock) Release() error {
	err := syscall.Flock(int(l.f.Fd()), syscall.LOCK_UN)
	if cerr := l.f.Close(); err == nil {
		err = cerr
	}
	return err
}

// TryLockFile asks for a shared or an exclusive lock on path, without a
// wait. It returns nil and no error when another open file has a lock that
// conflicts. The file must exist.
func TryLockFile(path, mode string) (*Lock, error) {
	var op int
	switch mode {
	case "shared":
		op = syscall.LOCK_SH
	case "exclusive":
		op = syscall.LOCK_EX
	default:
		return nil, fmt.Errorf("lock mode %q", mode)
	}
	// flock locks belong to the open file, so each call opens the file again.
	f, err := os.OpenFile(path, os.O_RDWR, 0)
	if err != nil {
		return nil, err
	}
	if err := syscall.Flock(int(f.Fd()), op|syscall.LOCK_NB); err != nil {
		f.Close()
		if errors.Is(err, syscall.EWOULDBLOCK) {
			return nil, nil
		}
		return nil, &os.PathError{Op: "flock", Path: path, Err: err}
	}
	return &Lock{f}, nil
}

// TryLock is the entry of the cases: it takes held, then asks for want.
func TryLock(path, held, want string) (bool, error) {
	if held != "none" {
		first, err := TryLockFile(path, held)
		if err != nil {
			return false, err
		}
		defer first.Release()
	}
	second, err := TryLockFile(path, want)
	if err != nil || second == nil {
		return false, err
	}
	return true, second.Release()
}
lock_file_test.go 79 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/lock-a-file/.

//go:build unix

package lockfile

import (
	"errors"
	"io/fs"
	"os"
	"path/filepath"
	"testing"
)

func data(t *testing.T) string {
	t.Helper()
	path := filepath.Join(t.TempDir(), "data.txt")
	if err := os.WriteFile(path, []byte("alpha\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	return path
}

func TestCases(t *testing.T) {
	cases := []struct {
		name, held, want string
		expect           bool
	}{
		{"no-lock-exclusive", "none", "exclusive", true},
		{"no-lock-shared", "none", "shared", true},
		{"exclusive-with-exclusive", "exclusive", "exclusive", false},
		{"shared-with-shared", "shared", "shared", true},
		{"shared-with-exclusive", "shared", "exclusive", false},
		{"exclusive-with-shared", "exclusive", "shared", false},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			path := data(t)
			got, err := TryLock(path, c.held, c.want)
			if err != nil || got != c.expect {
				t.Fatalf("got %v, %v; want %v", got, err, c.expect)
			}
			if b, _ := os.ReadFile(path); string(b) != "alpha\n" {
				t.Fatalf("the file holds %q", b)
			}
		})
	}
}

func TestReleaseFreesTheLock(t *testing.T) {
	path := data(t)
	l, err := TryLockFile(path, "exclusive")
	if err != nil || l == nil {
		t.Fatal("no first lock", err)
	}
	if l2, err := TryLockFile(path, "exclusive"); err != nil || l2 != nil {
		t.Fatal("a second exclusive lock", err)
	}
	if err := l.Release(); err != nil {
		t.Fatal(err)
	}
	l3, err := TryLockFile(path, "exclusive")
	if err != nil || l3 == nil {
		t.Fatal("no lock after the release", err)
	}
	l3.Release()
}

func TestMissingFile(t *testing.T) {
	dir := t.TempDir()
	_, err := TryLockFile(filepath.Join(dir, "missing.txt"), "exclusive")
	if !errors.Is(err, fs.ErrNotExist) {
		t.Fatalf("got %v, want not exist", err)
	}
	if entries, _ := os.ReadDir(dir); len(entries) != 0 {
		t.Fatal("the call made a file")
	}
}
lock_file.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/lock-a-file/.

//! Takes advisory locks on files with `File::try_lock` and
//! `File::try_lock_shared` (Rust 1.89 and later). On Unix they call flock, so
//! the lock belongs to the open file, and a drop of the `File` releases it.

use std::fs::{File, OpenOptions, TryLockError};
use std::io;
use std::path::Path;

/// Asks for a shared or an exclusive lock on `path`, without a wait. It
/// returns `Ok(None)` when another open file has a lock that conflicts. The
/// lock lives as long as the returned `File`. The file must exist.
pub fn try_lock_file(path: &Path, exclusive: bool) -> io::Result<Option<File>> {
    let f = OpenOptions::new().read(true).write(true).open(path)?;
    let got = if exclusive { f.try_lock() } else { f.try_lock_shared() };
    match got {
        Ok(()) => Ok(Some(f)),
        Err(TryLockError::WouldBlock) => Ok(None),
        Err(TryLockError::Error(e)) => Err(e),
    }
}

/// The entry of the cases: takes `held` ("none", "shared" or "exclusive"),
/// then asks for `want`.
pub fn try_lock(path: &Path, held: &str, want: &str) -> io::Result<bool> {
    let _first = match held {
        "none" => None,
        mode => try_lock_file(path, mode == "exclusive")?,
    };
    let second = try_lock_file(path, want == "exclusive")?;
    Ok(second.is_some())
}
tests/lock_file_test.rs 66 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/lock-a-file/.

use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;

use algo_lock_a_file::{try_lock, try_lock_file};

struct Tree(PathBuf);

impl Tree {
    fn new(name: &str) -> Tree {
        let dir = std::env::temp_dir().join(format!("lock-file-{}-{name}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("data.txt"), "alpha\n").unwrap();
        Tree(dir)
    }

    fn data(&self) -> PathBuf {
        self.0.join("data.txt")
    }
}

impl Drop for Tree {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

const CASES: &[(&str, &str, &str, bool)] = &[
    ("no-lock-exclusive", "none", "exclusive", true),
    ("no-lock-shared", "none", "shared", true),
    ("exclusive-with-exclusive", "exclusive", "exclusive", false),
    ("shared-with-shared", "shared", "shared", true),
    ("shared-with-exclusive", "shared", "exclusive", false),
    ("exclusive-with-shared", "exclusive", "shared", false),
];

#[test]
fn cases() {
    for (name, held, want, expect) in CASES {
        let t = Tree::new(name);
        assert_eq!(try_lock(&t.data(), held, want).unwrap(), *expect, "{name}");
        assert_eq!(fs::read_to_string(t.data()).unwrap(), "alpha\n", "{name}");
    }
}

#[test]
fn drop_frees_the_lock() {
    let t = Tree::new("drop");
    let first = try_lock_file(&t.data(), true).unwrap();
    assert!(first.is_some());
    assert!(try_lock_file(&t.data(), true).unwrap().is_none());
    drop(first);
    assert!(try_lock_file(&t.data(), true).unwrap().is_some());
}

#[test]
fn missing_file() {
    let t = Tree::new("missing");
    let err = try_lock_file(&t.0.join("missing.txt"), true).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
    assert!(!t.0.join("missing.txt").exists());
}
lock_file.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/lock-a-file/.

# The flock command of util-linux takes flock locks from a shell. Linux has
# it; macOS and the BSDs do not have it by default.

# try_lock_file FD MODE
# Asks for a shared or an exclusive lock on the file open as descriptor FD,
# without a wait. It returns status 0 with the lock, and status 1 when another
# open file has a lock that conflicts. Close FD, or call unlock_file FD, to
# release the lock.
try_lock_file() {
  local fd=$1 mode=$2
  case $mode in
    shared) flock --nonblock --shared "$fd" ;;
    exclusive) flock --nonblock --exclusive "$fd" ;;
    *) printf 'try_lock_file: bad mode: %s\n' "$mode" >&2; return 2 ;;
  esac
}

# unlock_file FD releases the lock on descriptor FD.
unlock_file() {
  flock --unlock "$1"
}

# try_lock PATH HELD WANT
# The entry of the cases: takes HELD with one open of PATH, then asks for WANT
# with a second open. It prints true or false. It returns status 1 when PATH
# does not exist; the function does not make the file.
try_lock() {
  local path=$1 held=$2 want=$3 first second result=false
  if [[ ! -f $path ]]; then
    printf 'try_lock: %s: No such file\n' "$path" >&2
    return 1
  fi
  # {name}< opens the file read-only on a new descriptor; < does not make it.
  exec {first}<"$path"
  if [[ $held != none ]]; then try_lock_file "$first" "$held" || { exec {first}<&-; return 1; }; fi
  exec {second}<"$path"
  if try_lock_file "$second" "$want"; then result=true; fi
  exec {second}<&- {first}<&-
  printf '%s\n' "$result"
}
test_lock_file.bats 40 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/lock-a-file/.

bats_require_minimum_version 1.5.0

setup() {
  command -v flock >/dev/null || skip "the flock command of util-linux is not installed"
  source "$BATS_TEST_DIRNAME/lock_file.sh"
  dir=$BATS_TEST_TMPDIR/tree
  mkdir -p "$dir"
  printf 'alpha\n' > "$dir/data.txt"
}

check() {
  run -0 try_lock "$dir/data.txt" "$1" "$2"
  [ "$output" = "$3" ]
  [ "$(cat "$dir/data.txt")" = alpha ]
}

@test "no-lock-exclusive" { check none exclusive true; }
@test "no-lock-shared" { check none shared true; }
@test "exclusive-with-exclusive" { check exclusive exclusive false; }
@test "shared-with-shared" { check shared shared true; }
@test "shared-with-exclusive" { check shared exclusive false; }
@test "exclusive-with-shared" { check exclusive shared false; }

@test "unlock-frees-the-lock" {
  exec {a}<"$dir/data.txt" {b}<"$dir/data.txt"
  try_lock_file "$a" exclusive
  ! try_lock_file "$b" exclusive
  unlock_file "$a"
  try_lock_file "$b" exclusive
  exec {a}<&- {b}<&-
}

@test "missing-file" {
  run -1 try_lock "$dir/missing.txt" none exclusive
  [ ! -e "$dir/missing.txt" ]
}

References

  1. Linux manual page, flock(2), DESCRIPTION, NFS details, NOTES
  2. Linux manual page, fcntl_locking(2), Advisory record locking, Open file description locks
  3. The Open Group Base Specifications Issue 8 (POSIX.1-2024), fcntl, DESCRIPTION (F_SETLK)
  4. Linux manual page, flock(1), DESCRIPTION, OPTIONS
  5. SQLite, How To Corrupt An SQLite Database File, 2.2 Posix advisory locks canceled by a separate thread doing close()
  6. The Python Standard Library, fcntl, The fcntl and ioctl system calls, fcntl.flock, fcntl.lockf
  7. Java SE 25 API, FileChannel, tryLock(long, long, boolean)
  8. Java SE 25 API, FileLock, Description, Platform dependencies
  9. .NET API reference, FileShare Enum, Fields, Remarks
  10. What's new in the .NET 11 runtime, Advisory file locking on iOS and tvOS
  11. .NET 6 breaking change, FileStream locks files with shared lock on Unix, New behavior
  12. Go standard library, package syscall, func Flock
  13. The Rust Standard Library, std::fs::File, try_lock, try_lock_shared, Platform-specific behavior

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source