Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
Modern PHP 8.x & Internals 5-8 Years (Senior) Medium Production Scenario

How do you handle Deadlocks and Race Conditions in file-based locks (`flock`) across multi-process PHP scripts?

Real-World Scenario / Incident Description

Multiple CLI cron jobs writing to the same shared log/cache file were corrupting file contents and hanging indefinitely.

657 views • Updated 1 month ago

Non-Blocking File Locking Pattern

$fp = fopen('/tmp/cron_task.lock', 'c+');

// LOCK_EX (Exclusive lock) | LOCK_NB (Non-blocking: fail immediately if locked)
if (! flock($fp, LOCK_EX | LOCK_NB)) {
    echo "Another process is already executing this task. Exiting.\n";
    fclose($fp);
    exit(0);
}

try {
    // Critical section execution
    executeHeavyBatchJob();
} finally {
    flock($fp, LOCK_UN); // Release lock
    fclose($fp);
}
Related Concepts: #flock #File Locks #Race Conditions #Concurrency