PHP:如何启动分离进程?

前端之家收集整理的这篇文章主要介绍了PHP:如何启动分离进程?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
目前我的解决方案是:
exec('PHP file.PHP >/dev/null 2>&1 &');

并在file.PHP

if (posix_getpid() != posix_getsid(getmypid()))
    posix_setsid();

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

不能用exec()(也不是shell_exec()或system())来做到这一点

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

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;
    }
}

这样叫:

$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;
原文链接:https://www.f2er.com/php/137867.html

猜你在找的PHP相关文章