Skip to content

Instantly share code, notes, and snippets.

@frak
Last active December 28, 2015 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frak/7529320 to your computer and use it in GitHub Desktop.
Save frak/7529320 to your computer and use it in GitHub Desktop.
How to lock a CLI script without leaving artefacts
<?php
/**
* Lock files are no end of pain, especially ensuring they are correctly removed when things blow up.
* This way there are never any artifacts left around, so nothing to clean up.
*/
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if($socket === false) {
throw new \Exception("Cannot create a socket, please check system configuration");
}
if(@socket_bind($socket, '127.0.0.1', self::LOCK_PORT) === false) {
$output->writeln('<error>This command is already running</error>');
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment