flock

flock(resource $stream, int $operation, int &$would_block = null): bool

Applies an advisory lock to an open stream: LOCK_SH shared read / LOCK_EX exclusive write / LOCK_NB non-blocking / LOCK_UN release - the classic tool for multi-process write safety.

C C23

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

int main(void) {
    /* flock(2): advisory locks with LOCK_SH / LOCK_EX / LOCK_NB */
    char path[64];
    snprintf(path, sizeof(path), "/tmp/a43_flock_c_%d", (int)getpid());
    int fd1 = open(path, O_RDWR | O_CREAT, 0644);
    int fd2 = open(path, O_RDWR, 0644);
    /* Exclusive lock on fd1 succeeds */
    printf("first exclusive lock: %s\n", flock(fd1, LOCK_EX) == 0 ? "true" : "false");
    /* A second fd cannot take it; LOCK_NB fails immediately with EWOULDBLOCK */
    int rc = flock(fd2, LOCK_EX | LOCK_NB);
    printf("second non-blocking: %s\n", rc == 0 ? "true" : "false");
    printf("would block: %s\n", rc == -1 && errno == EWOULDBLOCK ? "true" : "false");
    /* Release, then a shared read lock succeeds */
    flock(fd1, LOCK_UN);
    printf("released; shared lock: %s\n", flock(fd1, LOCK_SH) == 0 ? "true" : "false");
    close(fd1);
    close(fd2);
    unlink(path);
    return 0;
}
Output
first exclusive lock: true
second non-blocking: false
would block: true
released; shared lock: true

C++ C++26

C++26
#include <cerrno>
#include <cstdio>
#include <fcntl.h>
#include <sys/file.h>
#include <unistd.h>

int main() {
    // flock(2) works unchanged in C++ (sys/file.h)
    char path[64];
    std::snprintf(path, sizeof(path), "/tmp/a43_flock_cpp_%d", (int)getpid());
    int fd1 = open(path, O_RDWR | O_CREAT, 0644);
    int fd2 = open(path, O_RDWR, 0644);
    // Exclusive lock on fd1 succeeds
    std::printf("first exclusive lock: %s\n", flock(fd1, LOCK_EX) == 0 ? "true" : "false");
    // A second fd cannot take it; LOCK_NB fails immediately with EWOULDBLOCK
    int rc = flock(fd2, LOCK_EX | LOCK_NB);
    std::printf("second non-blocking: %s\n", rc == 0 ? "true" : "false");
    std::printf("would block: %s\n", rc == -1 && errno == EWOULDBLOCK ? "true" : "false");
    // Release, then a shared read lock succeeds
    flock(fd1, LOCK_UN);
    std::printf("released; shared lock: %s\n", flock(fd1, LOCK_SH) == 0 ? "true" : "false");
    close(fd1);
    close(fd2);
    unlink(path);
    return 0;
}
Output
first exclusive lock: true
second non-blocking: false
would block: true
released; shared lock: true

C# v11.0.100

v11.0.100
// .NET has no flock; an exclusive FileShare.None open is the approximation:
// the OS rejects a second open until the holder releases
var path = Path.Combine(Path.GetTempPath(), "a43_lock_cs");
var holder = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
Console.WriteLine("first exclusive open: true");
try
{
    using var second = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
    Console.WriteLine("second exclusive open: true");
}
catch (IOException)
{
    Console.WriteLine("second exclusive open: false");
}
holder.Dispose(); // release = close the handle
using var after = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
Console.WriteLine("after release, reopen: true");
File.Delete(path);
Output
first exclusive open: true
second exclusive open: false
after release, reopen: true

Go v1.27.4

v1.27.4
package main

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

func main() {
	// syscall.Flock: advisory locks with LOCK_SH / LOCK_EX / LOCK_NB
	path := "/tmp/a43_flock_go"
	f1, _ := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0644)
	f2, _ := os.OpenFile(path, os.O_RDWR, 0644)
	// Exclusive lock on handle 1 succeeds
	if err := syscall.Flock(int(f1.Fd()), syscall.LOCK_EX); err != nil {
		panic(err)
	}
	fmt.Println("first exclusive lock: true")
	// A second handle cannot take it; LOCK_NB fails immediately
	err := syscall.Flock(int(f2.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
	fmt.Println("second non-blocking:", err == nil)
	fmt.Println("would block:", err == syscall.EWOULDBLOCK)
	// Release, then a shared read lock succeeds
	syscall.Flock(int(f1.Fd()), syscall.LOCK_UN)
	syscall.Flock(int(f1.Fd()), syscall.LOCK_SH)
	fmt.Println("released; shared lock: true")
	f1.Close()
	f2.Close()
	os.Remove(path)
}
Output
first exclusive lock: true
second non-blocking: false
would block: true
released; shared lock: true

Java v27.0.1

v27.0.1
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        // FileChannel.lock/tryLock: OS-backed locks, but accounted per JVM -
        // a second channel in the SAME JVM throws instead of blocking
        Path path = Files.createTempFile("a43_flock_java", ".lock");
        try (FileChannel ch1 = new RandomAccessFile(path.toFile(), "rw").getChannel();
             FileChannel ch2 = new RandomAccessFile(path.toFile(), "rw").getChannel()) {
            // Exclusive lock on channel 1 succeeds (blocking)
            FileLock l1 = ch1.lock();
            System.out.println("first exclusive lock: " + (l1 != null));
            // Same-JVM second attempt throws OverlappingFileLockException
            try {
                FileLock l2 = ch2.tryLock();
                System.out.println("second non-blocking: " + (l2 != null));
            } catch (OverlappingFileLockException e) {
                System.out.println("second non-blocking: false (per-JVM accounting)");
            }
            // Release, then a shared read lock succeeds
            l1.release();
            FileLock l3 = ch1.lock(0, Long.MAX_VALUE, true);
            System.out.println("released; shared lock: " + (l3 != null));
            l3.release();
        }
        Files.delete(path);
    }
}
Output
first exclusive lock: true
second non-blocking: false (per-JVM accounting)
released; shared lock: true

JavaScript v26.13.1

v26.13.1
import { openSync, closeSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

// Node has no file-lock API - an exclusive-create lockfile (flag "wx") is the
// hand-rolled approximation of flock's LOCK_EX | LOCK_NB semantics
const path = join(tmpdir(), "a43_lock_js");
let fd = openSync(path, "wx"); // exclusive create: atomic take-the-lock
console.log("first exclusive create: true");
try {
  openSync(path, "wx"); // second taker: EEXIST immediately (non-blocking)
  console.log("second non-blocking: true");
} catch (e) {
  console.log("second non-blocking: false");
  console.log("failure code:", e.code);
}
closeSync(fd);
unlinkSync(path); // release = delete the lockfile
let reopened = false;
try {
  fd = openSync(path, "wx");
  reopened = true;
  closeSync(fd);
} finally {
  unlinkSync(path);
}
console.log("after release, take again:", reopened);
Output
first exclusive create: true
second non-blocking: false
failure code: EEXIST
after release, take again: true

PHP v8.6.0

v8.6.0
// flock: advisory locks - LOCK_SH, LOCK_EX, LOCK_NB (non-blocking)
$f1 = fopen(tempnam(sys_get_temp_dir(), 'lk'), 'r+');
$f2 = fopen(stream_get_meta_data($f1)['uri'], 'r+');
// Exclusive lock on handle 1 succeeds
var_dump(flock($f1, LOCK_EX));
// A second handle cannot take it: non-blocking attempt fails immediately
$wouldBlock = false;
var_dump(flock($f2, LOCK_EX | LOCK_NB, $wouldBlock));
var_dump($wouldBlock); // 1: the lock is held by the other handle
// Release, then a shared read lock succeeds
flock($f1, LOCK_UN);
var_dump(flock($f1, LOCK_SH));
// And an exclusive request from the second handle again loses
$wouldBlock = false;
var_dump(flock($f2, LOCK_EX | LOCK_NB, $wouldBlock));
var_dump($wouldBlock);
unlink(stream_get_meta_data($f1)['uri']);
Output
bool(true)
bool(false)
int(1)
bool(true)
bool(false)
int(1)

Python v3.15.2

v3.15.2
import fcntl
import os

# fcntl.flock: advisory locks with LOCK_SH / LOCK_EX / LOCK_NB
path = "/tmp/a43_flock_py"
f1 = open(path, "w+")
f2 = open(path, "w+")
# Exclusive lock on handle 1 succeeds
fcntl.flock(f1, fcntl.LOCK_EX)
print("first exclusive lock: True")
# A second handle cannot take it; LOCK_NB makes the attempt fail immediately
would_block = False
try:
    fcntl.flock(f2, fcntl.LOCK_EX | fcntl.LOCK_NB)
    got = True
except BlockingIOError:
    got = False
    would_block = True
print("second non-blocking:", got)
print("would block:", would_block)
# Release, then a shared read lock succeeds
fcntl.flock(f1, fcntl.LOCK_UN)
fcntl.flock(f1, fcntl.LOCK_SH)
print("released; shared lock: True")
f1.close()
f2.close()
os.unlink(path)
Output
first exclusive lock: True
second non-blocking: False
would block: True
released; shared lock: True

Rust v1.99.1

v1.99.1
use std::fs::OpenOptions;
use std::os::unix::io::AsRawFd;

fn main() {
    // libc::flock: advisory locks with LOCK_SH / LOCK_EX / LOCK_NB
    let path = "/tmp/a43_flock_rs";
    let f1 = OpenOptions::new().read(true).write(true).create(true).open(path).unwrap();
    let f2 = OpenOptions::new().read(true).write(true).open(path).unwrap();
    // Exclusive lock on handle 1 succeeds
    let rc1 = unsafe { libc::flock(f1.as_raw_fd(), libc::LOCK_EX) };
    println!("first exclusive lock: {}", rc1 == 0);
    // A second handle cannot take it; LOCK_NB fails immediately
    let rc2 = unsafe { libc::flock(f2.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
    println!("second non-blocking: {}", rc2 == 0);
    println!("would block: {}", rc2 == -1 && std::io::Error::last_os_error().raw_os_error() == Some(libc::EWOULDBLOCK));
    // Release, then a shared read lock succeeds
    unsafe { libc::flock(f1.as_raw_fd(), libc::LOCK_UN) };
    let rc3 = unsafe { libc::flock(f1.as_raw_fd(), libc::LOCK_SH) };
    println!("released; shared lock: {}", rc3 == 0);
    drop(f1);
    drop(f2);
    std::fs::remove_file(path).unwrap();
}
Output
first exclusive lock: true
second non-blocking: false
would block: true
released; shared lock: true

TypeScript v26.13.1

v26.13.1
import { openSync, closeSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

// Node has no file-lock API - an exclusive-create lockfile (flag "wx") is the
// hand-rolled approximation of flock's LOCK_EX | LOCK_NB semantics
const path = join(tmpdir(), "a43_lock_ts");
let fd = openSync(path, "wx"); // exclusive create: atomic take-the-lock
console.log("first exclusive create: true");
try {
  openSync(path, "wx"); // second taker: EEXIST immediately (non-blocking)
  console.log("second non-blocking: true");
} catch (e) {
  console.log("second non-blocking: false");
  console.log("failure code:", (e as NodeJS.ErrnoException).code);
}
closeSync(fd);
unlinkSync(path); // release = delete the lockfile
let reopened = false;
try {
  fd = openSync(path, "wx");
  reopened = true;
  closeSync(fd);
} finally {
  unlinkSync(path);
}
console.log("after release, take again:", reopened);
Output
first exclusive create: true
second non-blocking: false
failure code: EEXIST
after release, take again: true

Language differences

C: flock(2) (<sys/file.h>) is the original - a second fd on the same file fails immediately with EWOULDBLOCK for LOCK_EX|LOCK_NB; LOCK_UN releases.

C++: same flock(2) as C; there is no standard file lock in C++17 (std::filesystem does not cover locks).

C#: no flock - the usual approximation is a FileShare.None exclusive open (the OS rejects a second open until release); for richer cross-process locking use a named Mutex.

Go: syscall.Flock (Unix) maps flock(2) one-to-one; on Windows switch to LockFileEx.

Java: FileChannel.lock()/tryLock() is an OS lock accounted per JVM - a second channel in the SAME JVM throws OverlappingFileLockException on an overlapping lock (demonstrated honestly in the example); across processes it manifests as blocking or a failed tryLock.

JavaScript: Node has no file lock - the norm is a hand-rolled lockfile (openSync(path, "wx") exclusive create; EEXIST is the non-blocking failure) or the proper-lockfile package; release = delete the file.

PHP: flock($stream, LOCK_EX) blocks by default, LOCK_EX|LOCK_NB fails immediately and sets would_block to 1; LOCK_SH is the shared read; the lock is released automatically at fclose; the manual flags it as unreliable on NFS, and it is advisory (non-participants are unprotected); behavior has extra caveats under threaded SAPIs.

Python: fcntl.flock (Unix native) - a non-blocking failure raises BlockingIOError (equivalent to EWOULDBLOCK); leaving the with open block unlocks implicitly (fd closed).

Rust: no file lock in std - libc::flock (unsafe) mirrors C; the fs2/fd-lock crates offer RAII wrappers (Drop unlocks).

TypeScript: same as JavaScript - the "wx" lockfile approximation.