PHP: how to start a detached process?

后端 未结 2 1183
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 05:20

Currently my solution is:

exec(\'php file.php >/dev/null 2>&1 &\');

and in file.php

if (posix_getpid() != pos         


        
2条回答
  •  长发绾君心
    2021-01-12 05:42

    Provided your current user has sufficient permissions to do so this should be possible with exec and alike:

    /*
    / Start your child (otherscript.php)
    */
    function startMyScript() {
        exec('nohup php otherscript.php > nohup.out & > /dev/null');
    }
    
    /*
    / Kill the script (otherscript.php)
    / NB: only kills one process at the time, otherwise simply expand to 
    / loop over all complete exec() output rows
    */
    function stopMyScript() {
        exec('ps a | grep otherscript.php | grep -v grep', $otherProcessInfo);
        $otherProcessInfo = array_filter(explode(' ', $otherProcessInfo[0]));
        $otherProcessId = $otherProcessInfo[0];
        exec("kill $otherProcessId");
    }
    
    // ensure child is killed when parent php script / process exits
    register_shutdown_function('stopMyScript');
    
    startMyScript();
    

提交回复
热议问题