Skip to content

Instantly share code, notes, and snippets.

@avargas
Created November 5, 2015 16:21

Revisions

  1. avargas created this gist Nov 5, 2015.
    45 changes: 45 additions & 0 deletions run-lock.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    <?php


    // simple lock, prevent script from running multiple times at once
    $lockfile = '/tmp/.run.php-lock-' . md5(implode('', array_slice($argv, 1)));
    if (($lock = fopen($lockfile, 'w+')) === false) {
    echo "fopen($lockfile) failed\n";
    die(-1);
    }

    // lock that bitch
    if (flock($lock, LOCK_EX | LOCK_NB) === false) {
    echo "flock($lockfile) failed - possibly already running?\n";
    die(-1);
    }

    $unlock = function() use (&$lock, $lockfile) {
    printf("unlocking %s\n", $lockfile);

    if (is_resource($lock)) {
    fclose($lock);
    }

    if (file_exists($lockfile)) {
    unlink($lockfile);
    }
    };

    // just in case something fails, clean up
    register_shutdown_function($unlock);

    // create the actual command

    array_shift($argv);

    $command = [];
    foreach ($argv as $arg) {
    $command[] = '"' . str_replace('"', '\"', $arg) . '"';
    }

    $command = implode(' ', $command);

    echo "running $command\n\n";

    passthru($command);