45
54

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

プロセスの多重起動をアドバイザリロックで防止する for PHP

Posted at

これ↓の PHP 版です。

<?php
function single()
{
    static $fp;
    $fp = fopen(__FILE__, "r");

    if (is_resource($fp) == false)
    {
        throw new \RuntimeException("unable open self");
    }

    $wouldBlock = false;

    if (flock($fp, LOCK_EX|LOCK_NB, $wouldBlock) == false)
    {
        if ($wouldBlock)
        {
            return false;
        }

        throw new \RuntimeException("unable lock self");
    }

    return true;
}

if (single() == false)
{
    echo "process is running.\n";
    exit();
}

$pid = getmypid();
echo "pid $pid\n";
echo "wait 10 sec ";

for ($i=0; $i<10; $i++)
{
    sleep(1);
    echo ".";
}

echo "\n";

この方法なら後処理のことはなにも考えなくてもカーネルがよきに計らってくれます。kill -KILL $pid で殺されても大丈夫です。

45
54
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
45
54

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?