Skip to content

Instantly share code, notes, and snippets.

@hedenface
Created February 27, 2018 21:21
Show Gist options
  • Save hedenface/e7ba3f747cdd1e8a91ddfba9764d5ff6 to your computer and use it in GitHub Desktop.
Save hedenface/e7ba3f747cdd1e8a91ddfba9764d5ff6 to your computer and use it in GitHub Desktop.
php: Basic flock() example
<?php
/*
basic flock() example
1. open 2 terminals
2. in first terminal, execute `./basic_flock_example.php --first`
3. then *quickly* in second terminal, execute `./basic_flock_example --second`
4. once both have finished, view the output file: `cat file`
*/
$longopts = array('first', 'second');
$opts = getopt('', $longopts);
if (isset($opts['second'])) {
run_trying_to_access_file_with_lock();
} else {
create_and_write_to_a_file_with_lock();
}
function create_and_write_to_a_file_with_lock() {
$seconds = 10;
echo "Locking a file and writing for {$seconds} seconds before unlocking...\n";
$handle = fopen("file", "a");
if ($handle === false) {
die("Unable to open `file` for appending. Check your permissions!\n");
}
echo "Opened `file`...\n";
// attempt to lock the file
if (flock($handle, LOCK_EX)) {
echo "Obtained the lock...\n";
for ($i = 1; $i < $seconds + 1; $i++) {
fwrite($handle, "--first\n");
sleep(1);
echo "{$i}...\n";
}
echo "Unlocking `file`...\n";
flock($handle, LOCK_UN);
} else {
echo "Unable to acquire lock on `file`!\n";
}
fclose($handle);
echo "Closed `file`...\n";
echo "Done!\n";
}
function run_trying_to_access_file_with_lock() {
echo "Attempting to write to a file which is locked by another process...\n";
$handle = fopen("file", "a");
if ($handle === false) {
die("Unable to open `file` for appending. Check your permissions!\n");
}
echo "Opened `file`...\n";
// flock() blocks waiting to lock
// you can adjust this behavior by adding
// LOCK_NB to the second paramter ($operation):
// LOCK_EX | LOCK_NB
if (flock($handle, LOCK_EX)) {
echo "Obtained the lock...\n";
fwrite($handle, "--second\n");
echo "Unlocking `file`...\n";
flock($handle, LOCK_UN);
} else {
echo "Unable to acquire lock on `file`!\n";
}
fclose($handle);
echo "Closed `file`...\n";
echo "Done!\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment