检查php进程是否已在运行

Bor*_*tex 6 php file-exists

我正在尝试使用临时文件demo.lock检查进程是否已在运行:

demo.php:

<?php
    $active=file_exists('demo.lock');
    if ($active)
    {
        echo 'process already running';
    }
    else
    {
        file_put_contents ('demo.lock', 'demo');
        sleep(10);  //do some job
        unlink ('demo.lock');
        echo 'job done';
    }
?>
Run Code Online (Sandbox Code Playgroud)

但它似乎不起作用:如果我打开demo.php两次它总是显示"完成工作",也许是因为它认为它是相同的过程?有什么方法可以做到吗?我也尝试使用类似结果的getmypid().

谢谢

Bor*_*tex -1

好吧,发送一些标题和刷新似乎对我有用(不知道为什么),所以现在当我加载页面时显示“开始”,如果我在完成该过程之前点击浏览器上的刷新按钮,则会出现警告消息:

<?php

$file = @fopen("demo.lock", "x");
if($file === false)
{
    echo "Unable to acquire lock; either this process is already running, or permissions are insufficient to create the required file\n";
    exit;
}

header("HTTP/1.0 200 OK");
ob_start();
echo "Starting";
header('Content-Length: '.ob_get_length(),true);
ob_end_flush();
flush();

fclose($file); // the fopen call created the file already
sleep(10); // do some job
unlink("demo.lock");    
?>
Run Code Online (Sandbox Code Playgroud)

感谢迄今为止所有的答案和建议