2

我正在使用execPHP 中的函数来运行命令。我正在运行的命令通常会花费相当多的时间,而且我不需要阅读它的输出。exec有没有一种简单的方法告诉 PHP在继续执行脚本的其余部分之前不要等待命令完成?

4

3 回答 3

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.

于 2012-09-28T07:44:53.417 回答
1

这是我使用的(您可以使用 exec 或 system 代替 paasthru):

passthru("/path/to/program args >> /path/to/logfile 2>&1 &");
于 2012-09-28T07:33:45.623 回答
1

您要查找的内容称为异步调用,如下所示:

PHP中的异步shell exec

php执行一个后台进程

PHP exec() 作为后台进程(Windows Wampserver 环境)

于 2012-09-28T07:35:58.023 回答