PHP:如何启动分离进程?

Dal*_*ius 8 php linux parallel-processing

目前我的解决方案是:

exec('php file.php >/dev/null 2>&1 &');
Run Code Online (Sandbox Code Playgroud)

并在file.php中

if (posix_getpid() != posix_getsid(getmypid()))
    posix_setsid();
Run Code Online (Sandbox Code Playgroud)

我有什么方法可以用exec做到这一点?

hek*_*mgl 9

不,这不能做exec()(NOR shell_exec()或system())


如果您安装了pcntl扩展,它将是:

function detached_exec($cmd) {
    $pid = pcntl_fork();
    switch($pid) {
         // fork errror
         case -1 : return false

         // this code runs in child process
         case 0 :
             // obtain a new process group
             posix_setsid();
             // exec the command
             exec($cmd);
             break;

         // return the child pid in father
         default: 
             return $pid;
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样称呼它:

$pid = detached_exec($cmd);
if($pid === FALSE) {
    echo 'exec failed';
}

// do some work

// kill child
posix_kill($pid, SIGINT);
waitpid($pid, $status);

echo 'Child exited with ' . $status;
Run Code Online (Sandbox Code Playgroud)


Phi*_*zen 6

如果您当前的用户有足够的权限这样做,这应该是可能的exec和相似:

/*
/ 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();
Run Code Online (Sandbox Code Playgroud)

  • 请不要**再次这样做:http://stackoverflow.com/review/suggested-edits/3201462这绝对不是Stack Overflow的工作原理.你是方式,**方式**脱节,交出别人的答案,并指出他们自己的答案. (5认同)
  • 投票是我们在此处对内容进行排序的方式. (2认同)