UK
apps/winzik / src / Core / Relaunch.php · commit 6576d6f
<?phpnamespace App\Core;/** * WinZik started again once this one has ended (an update installed, the options reset): the new one finds the place * free and starts at once. * * Why: WinZik is alone thanks to a lock on var/winzik.lock. A program started by WinZik inherits its open files, that * lock included: the new WinZik held the old one's lock itself, waited for it, then thought "WinZik is already * running" and ended (a window not drawn, then nothing). So the launcher waits for this WinZik to end, and the lock * says whose it is (its pid): a lock whose WinZik is gone is taken over (takeLock). */final class Relaunch{    /**     * The shell script (Linux, macOS): $1 the pid to wait for, then the command.     */    public const SCRIPT = <<<'SH'pid=$1; shifti=0; while kill -0 "$pid" 2>/dev/null && [ $i -lt 300 ]; do sleep 0.1; i=$((i+1)); doneexec "$@"SH;    /** @param list<string> $command the program and its arguments (the WinZik to start) */    public static function afterExit(array $command): bool    {        if ($command === [] || $command[0] === '' || \JumPHP\Kernel\Platform::isHeadless()) {            return false;       // the tests: nothing is started        }        putenv('WINZIK_RELAUNCH=1');        // the new one waits a little for the lock if it is not free yet        $pid = getmypid();        if (PHP_OS_FAMILY === 'Windows') {            // PowerShell waits for this one to end, then starts the new one (Start-Process: no inherited handle)            $exe = str_replace("'", "''", $command[0]);            $args = implode(' ', array_map(fn ($a) => "'" . str_replace("'", "''", $a) . "'", array_slice($command, 1)));            $ps = "Wait-Process -Id $pid -Timeout 30 -ErrorAction SilentlyContinue; Start-Process -FilePath '$exe'" . ($args !== '' ? " -ArgumentList $args" : '');            $h = @popen('start "" /B powershell -NoProfile -WindowStyle Hidden -Command "' . $ps . '"', 'r');            if ($h === false) {                return false;            }            pclose($h);            return true;        }        $p = @proc_open(['/bin/sh', '-c', self::SCRIPT, 'sh', (string)$pid, ...$command],            [0 => ['file', '/dev/null', 'r'], 1 => ['file', '/dev/null', 'w'], 2 => ['file', '/dev/null', 'w']], $pipes);        return is_resource($p);    }    /**     * The lock that keeps WinZik alone: taken (it then holds this pid), or null when another WinZik is running. A lock     * held although its WinZik ended (a program it started inherited it: the new WinZik itself, ffmpeg, a helper) is     * taken over. $wait: seconds to wait for a WinZik that is ending.     * @return resource|null     */    public static function takeLock(string $path, float $wait = 0.0)    {        $lock = @fopen($path, 'c+');        if ($lock === false) {            return null;        }        $until = microtime(true) + $wait;        while (!flock($lock, LOCK_EX | LOCK_NB)) {            $owner = (int)trim((string)stream_get_contents($lock, 32, 0));            if ($owner > 0 && $owner !== getmypid() && function_exists('posix_kill') && !@posix_kill($owner, 0)) {                fclose($lock);                @unlink($path);         // the old file stays with whoever holds it; a new one, free                $lock = @fopen($path, 'c+');                if ($lock === false) {                    return null;                }                continue;            }            if (microtime(true) >= $until) {                fclose($lock);                return null;            }            usleep(100000);        }        ftruncate($lock, 0);        fwrite($lock, (string)getmypid());        fflush($lock);        return $lock;    }    /** @return list<string> how to start this WinZik again: its executable, else this PHP and app.php */    public static function command(): array    {        if (defined('JUMPHP_EXECUTABLE') && is_file((string)constant('JUMPHP_EXECUTABLE'))) {            return [(string)constant('JUMPHP_EXECUTABLE')];        }        return [PHP_BINARY, dirname(__DIR__, 2) . '/app.php'];    }}