所以我有一个主要的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功能的文件需要很长时间,所以我想将用户重定向到他来自的页面,而这个功能完成它的工作,因为它无论如何独立并将输出转储到其他地方
答案 0 :(得分:3)
这是使用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());
}
答案 1 :(得分:2)
我认为问题在于你的&符号并不是在正确的位置。试试这个:
$logFile = 'app-output.txt';
$command = '(nohup /export/php -r "require \'/export/wiki.php\';update_wiki(1);"';
$command.= ' > "'.$logFile.'" 2>&1) &';
exec($command);