Checking if process still running?

后端 未结 9 576
野的像风
野的像风 2020-11-30 03:55

As a way to build a poor-man\'s watchdog and make sure an application is restarted in case it crashes (until I figure out why), I need to write a PHP CLI script that will be

9条回答
  •  旧时难觅i
    2020-11-30 04:40

    If you're doing it in php, why not use php code:

    In the running program:

    define('PIDFILE', '/var/run/myfile.pid');
    
    file_put_contents(PIDFILE, posix_getpid());
    function removePidFile() {
        unlink(PIDFILE);
    }
    register_shutdown_function('removePidFile');   
    

    Then, in the watchdog program, all you need to do is:

    function isProcessRunning($pidFile = '/var/run/myfile.pid') {
        if (!file_exists($pidFile) || !is_file($pidFile)) return false;
        $pid = file_get_contents($pidFile);
        return posix_kill($pid, 0);
    }
    

    Basically, posix_kill has a special signal 0 that doesn't actually send a signal to the process, but it does check to see if a signal can be sent (the process is actually running).

    And yes, I do use this quite often when I need long running (or at least watchable) php processes. Typically I write init scripts to start the PHP program, and then have a cron watchdog to check hourly to see if it's running (and if not restart it)...

提交回复
热议问题