加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP:如何启动分离进程?

发布时间:2020-12-13 13:34:18 所属栏目:PHP教程 来源:网络整理
导读:目前我的解决方案是: exec('php file.php /dev/null 21 '); 并在file.php中 if (posix_getpid() != posix_getsid(getmypid())) posix_setsid(); 我有什么方法可以用exec做到这一点? 不能用exec()(也不是shell_exec()或system())来做到这一点 如果您安装了p
目前我的解决方案是:
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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读