Resource Deadlock Avoided
Production Risk
Deadlocks between long-running processes can halt production workflows. Add lock acquisition timeouts and deadlock detection.
The kernel detected that granting the requested lock would result in a deadlock with existing locks held by other processes. This is returned by fcntl POSIX file locking when the lock dependency graph forms a cycle.
- 1Process A holds a lock on file1 and is waiting for file2, while Process B holds file2 and is waiting for file1.
- 2Multiple processes acquire file locks in inconsistent orders.
- 3A database or file-locking library is using POSIX locks incorrectly.
Two processes waiting for locks held by each other.
// Process A: fcntl(fd_file1, F_SETLKW, &lock); // holds file1 fcntl(fd_file2, F_SETLKW, &lock); // waits for file2 -> EDEADLK // Process B simultaneously: fcntl(fd_file2, F_SETLKW, &lock); // holds file2 fcntl(fd_file1, F_SETLKW, &lock); // waits for file1
expected output
fcntl(F_SETLKW) returned -1, errno = EDEADLK (Resource deadlock avoided)
Fix
Acquire all locks in a globally consistent order
WHEN When multiple processes lock multiple resources
// Always acquire locks in sorted order by resource ID
void lock_two_files(int fd_a, int fd_b) {
if (fd_a < fd_b) {
lock(fd_a); lock(fd_b);
} else {
lock(fd_b); lock(fd_a);
}
}Why this works
A consistent global ordering of lock acquisition eliminates the possibility of circular wait, preventing deadlock.
✕ Ignore EDEADLK and retry immediately
The deadlock condition will persist until one of the processes releases its locks. Retrying without releasing locks will not resolve the deadlock.
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev