diff --git a/lock.inc.php b/lock.inc.php index 08b2bb4..f95cc5c 100644 --- a/lock.inc.php +++ b/lock.inc.php @@ -5,22 +5,45 @@ function gamectl_check_lock() { global $GAME_ROOT; + //let's check if are already in a locked environment if(getenv("GAMECTL_IN_LOCK")) return; - //don't bother with windows - if(DIRECTORY_SEPARATOR != '/') - 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)) { - echo "gamectl is locked. Waiting...\n"; - $pid = file_get_contents($lock); - if(!trim(exec("lsof -p $pid"))) + $pid = '0'; + try { - echo "Seems gamectl process is gone but lock still exists, proceeding..\n"; + $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; } @@ -29,9 +52,10 @@ function gamectl_check_lock() register_shutdown_function('taskman\\gamectl_unlock'); + //for spawned child processes putenv("GAMECTL_IN_LOCK=1"); - file_put_contents($lock, getmypid()); + file_put_contents($lock, getmypid(), LOCK_EX); } function gamectl_unlock()