PHP:如何启动分离进程?

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

并在file.PHP

  1. if (posix_getpid() != posix_getsid(getmypid()))
  2. posix_setsid();

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

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

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

  1. function detached_exec($cmd) {
  2. $pid = pcntl_fork();
  3. switch($pid) {
  4. // fork errror
  5. case -1 : return false
  6.  
  7. // this code runs in child process
  8. case 0 :
  9. // obtain a new process group
  10. posix_setsid();
  11. // exec the command
  12. exec($cmd);
  13. break;
  14.  
  15. // return the child pid in father
  16. default:
  17. return $pid;
  18. }
  19. }

这样叫:

  1. $pid = detached_exec($cmd);
  2. if($pid === FALSE) {
  3. echo 'exec Failed';
  4. }
  5.  
  6. // do some work
  7.  
  8. // kill child
  9. posix_kill($pid,SIGINT);
  10. waitpid($pid,$status);
  11.  
  12. echo 'Child exited with ' . $status;

猜你在找的PHP相关文章