php - 如何强制 PHP 脚本在调用 exec() 后继续执行脚本?

标签 php exec

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

最佳答案

// 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 即可运行。

关于php - 如何强制 PHP 脚本在调用 exec() 后继续执行脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12635375/

相关文章:

powershell - 如何从cmd执行ps1文件?

Go:按顺序接收 os.cmd stdout 和 stderr

bash - `read` 无法从重定向读取, `cat` 工作正常吗?

php - MySQL一对多,只从多个表中提取选定的记录

php - 使用 array_count_values 并得到 "Can only count STRING and INTEGER values!"错误

php - Web 应用程序性能改进

Java Runtime.getRuntime().exec() 似乎正在覆盖 $PATH

php - PHP 加密,IOS 解密

php - 新服务器 : Troubleshooting PostgreSQL Syntax Error

对 Unix 中 exec(family) 的使用感到困惑