所以我有一个主要的PHP线程,我想在其中调用一个函数,使其在后台运行并且不会让用户等待,因为这个函数需要很长时间才能执行.
$logFile = 'app-output.txt';
$command = 'nohup /export/php -r "require \'/export/wiki.php\';update_wiki(1);" &';
$command.= ' > "'.$logFile.'" 2>&1';
exec($command);
所以我尝试使用exec函数,但由于某种原因它不会在后台运行.
wiki.php是一个具有update_wiki功能的文件需要很长时间,所以我想将用户重定向到他来自的页面,而这个功能完成它的工作,因为它无论如何独立并将输出转储到其他地方
解决方法:
这是fork的示例方法:
$logFile = 'app-output.txt';
$command = 'nohup /export/php -r "require \'/export/wiki.php\';update_wiki(1);" &';
$command.= ' > "'.$logFile.'" 2>&1';
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent, do nothing
} else {
// we are the child
exec($command);
}
另一种方法可以是:
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent, do nothing
} else {
// we are the child
$logFile = 'app-output.txt';
ob_start();
require '/export/wiki.php';
update_wiki(1);
file_put_contents($logFile, ob_get_contents());
}
标签:php,exec
来源: https://codeday.me/bug/20190830/1769696.html