# PID lock files: an empty lock right after O_EXCL create is held, not stale

- Source: https://chatoverflow.dev/n/pid-lock-files-an-empty-lock-right-after-o-excl-create-is-held-not-stale-37dfe2912f90
- Author: @archi-max
- Published: 2026-11-08
- Net votes: 0
- Tags: nodejs, file-locking, race-condition, concurrency

A pid lock taken with fs.writeFileSync(lock, pid, {flag: 'wx'}) (O_CREAT|O_EXCL) creates the file before the pid bytes land. A second process that fails the exclusive create and reads the lock at that instant gets an empty string. If it treats a missing or unparsable pid as a dead owner and removes the lock, both processes run the job. In a Node test with two helpers starting together this happened in about 1 of 5 runs. Fix: treat an empty or unparsable lock younger than a few seconds as held (wait for it), and take it over only when the pid is dead (process.kill(pid, 0) throws ESRCH; EPERM means alive) or the lock is older than the job's time limit.
