2012-09-28 59 views
2

我使用PHP中的exec函数来运行命令。我运行的命令通常需要很长时间,我不需要读取它的输出。是否有一种简单的方式告诉PHP在继续执行脚本的其余部分之前不要等待exec命令完成?如何在调用exec()后强制PHP脚本继续使用脚本?

+0

也许它是作为一个单独的过程吗? – tradyblix

+0

我该怎么做呢?我只是将'&'追加到命令的末尾? –

+1

'exec(“nohup $ your_command&”)' - 运行命令免于hangups,输出到非tty('nohup'),在后台运行('&') – Nemoden

回答

2
// nohup_test.php: 

// a very long running process 
$command = 'tail -f /dev/null'; 
exec("nohup $command >/dev/null 2>/dev/null &"); // here we go 
printf('run command: %s'.PHP_EOL, $command); 
echo 'Continuing to execute the rest of this script instructions'.PHP_EOL; 

for ($x=1000000;$x-->0;) { 
    for ($y=1000000;$y-->0;) { 
    //this is so long, so I can do ps auwx | grep php while it's running and see whether $command run in separate process 
    } 
} 

运行nohup_test.php:

$ php nohup_test.php 
run command: tail -f /dev/null 
Continuing to execute the rest of this script instructions 

让我们来看看我们的流程的PID:

$ ps auwx | grep tail 
nemoden 3397 0.0 0.0 3252 636 pts/8 S+ 18:41 0:00 tail -f /dev/null 
$ ps auwx | grep php 
nemoden 3394 82.0 0.2 31208 6804 pts/8 R+ 18:41 0:04 php nohup_test.php 

,你可以看到,PID是不同的,我的脚本,而无需等待tail -f /dev/null运行。

+0

这太棒了。谢谢! –

+0

不用客气:) – Nemoden

+0

使用'/ dev/null'是正确工作的关键。由于某些原因,当我指定一个实际的日志文件位置(即@zaf建议的'/ path/to/logfile')时,PHP仍然等待该过程完成。任何想法,为什么这是? –

1

这里是我使用(你可以使用EXEC或系统代替paasthru):

passthru("/path/to/program args >> /path/to/logfile 2>&1 &"); 
+0

谢谢!不过,我并不太熟悉这里的一些语法。 '>>和'2>&1&'做什么? –

+0

>>将程序的输出发送到日志文件。 '2>&1'会将错误消息重定向到标准输出,基本上意味着所有的输出都会转到日志文件。 '&'表示在后台运行命令。 – zaf

+0

完美。谢谢! –

相关问题