taskman_lock/lock.inc.php

69 lines
1.3 KiB
PHP

<?php
namespace taskman;
function gamectl_check_lock()
{
global $GAME_ROOT;
//let's check if are already in a locked environment
if(getenv("GAMECTL_IN_LOCK"))
return;
$is_nix = DIRECTORY_SEPARATOR === '/';
$is_process_alive = $is_nix ?
function($pid) : bool
{
return !empty(trim(exec("lsof -p $pid")));
}
:
function($pid) : bool
{
$output = shell_exec("tasklist /FI \"PID eq $pid\" 2>NUL");
return strpos($output, "$pid") !== false;
};
$lock = $GAME_ROOT . '/gamectl.lock';
$last_pid = null;
while(file_exists($lock))
{
$pid = '0';
try
{
$pid = file_get_contents($lock);
}
catch(\Exception $e) {}
if($last_pid !== $pid)
{
echo "gamectl is locked by process ($pid). Waiting...\n";
$last_pid = $pid;
}
if(!$is_process_alive($pid))
{
echo "Seems gamectl process ($pid) is gone but lock still exists, proceeding..\n";
break;
}
sleep(1);
}
register_shutdown_function('taskman\\gamectl_unlock');
//for spawned child processes
putenv("GAMECTL_IN_LOCK=1");
file_put_contents($lock, getmypid(), LOCK_EX);
}
function gamectl_unlock()
{
global $GAME_ROOT;
$lock = $GAME_ROOT . '/gamectl.lock';
if(file_exists($lock))
unlink($lock);
}