我有一个PHP脚本,需要调用shell脚本,但根本不关心输出。shell脚本执行了许多SOAP调用,完成起来很慢,因此我不想在PHP请求等待应答时降低它的速度。事实上,PHP请求应该能够在不终止shell进程的情况下退出。

我已经研究了各种exec()、shell_exec()、pcntl_fork()等函数,但它们似乎都不能提供我想要的东西。(或者,即使他们这样做,我也不清楚是如何做到的。)有什么建议吗?


当前回答

我还发现Symfony Process Component在这方面很有用。

use Symfony\Component\Process\Process;

$process = new Process('ls -lsa');
// ... run process in background
$process->start();

// ... do other things

// ... if you need to wait
$process->wait();

// ... do things after the process has finished

在GitHub回购中查看它是如何工作的。

其他回答

我还发现Symfony Process Component在这方面很有用。

use Symfony\Component\Process\Process;

$process = new Process('ls -lsa');
// ... run process in background
$process->start();

// ... do other things

// ... if you need to wait
$process->wait();

// ... do things after the process has finished

在GitHub回购中查看它是如何工作的。

如果它“不关心输出”,脚本的exec不能被调用和后台进程?

编辑-结合@AdamTheHut对这篇文章的评论,你可以把它添加到对exec的调用中:

" > /dev/null 2>/dev/null &"

这将把stdio (first >)和stderr(2>)重定向到/dev/null并在后台运行。

做同样的事情还有其他方法,但这是最简单的。


上述双重定向的替代方法:

" &> /dev/null &"

我用at来做这个,因为它真的开始了一个独立的过程。

<?php
    `echo "the command"|at now`;
?>

我发现唯一对我有效的方法是:

shell_exec('./myscript.php | at now & disown')

做这件事的正确方法是

叉() 塞西德() execve()

Fork Fork, setsid告诉当前进程成为主进程(没有父进程),execve告诉调用进程被被调用进程取代。这样父母可以在不影响孩子的情况下退出。

 $pid=pcntl_fork();
 if($pid==0)
 {
   posix_setsid();
   pcntl_exec($cmd,$args,$_ENV);
   // child becomes the standalone detached process
 }

 // parent's stuff
 exit();