【问题标题】:How to run a php function in background separate from the main thread?如何在与主线程分开的后台运行 php 函数?
【发布时间】:2014-07-11 20:08:13
【问题描述】:

所以我有一个主 php 线程,我想在其中调用一个函数,使其在后台运行并且不会让用户等待,因为该函数需要很长时间才能执行。

$logFile = 'app-output.txt';
$command = 'nohup /export/php -r "require \'/export/wiki.php\';update_wiki(1);" &';
$command.= ' > "'.$logFile.'" 2>&1';
exec($command);

所以我尝试使用 exec 函数执行此操作,但由于某种原因它没有在后台运行。 WHere wiki.php 是具有 update_wiki 功能的文件,需要很长时间,所以我想将用户重定向回他来自的页面,而这个功能完成它的工作,因为它无论如何都是独立的并将输出转储到其他地方

【问题讨论】:

  • exec 不在后台运行,您需要pcntl-fork.php
  • 您能否详细说明如何使用 pcntl-fork 运行此 update_wiki()?

标签: php exec


【解决方案1】:

这是使用 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());
}

【讨论】:

  • 子进程执行完会自动死掉吗?
  • @user2601010 是的,一旦脚本完成 - 它会死
  • 这种方法有什么缺点或需要注意的地方吗?
  • @user2601010 通常 - 不,我在第二个中看到的唯一问题 - 如果 php 代码出现问题 - 日志文件将不会被保存,因此启用 php 错误日志记录和记录错误是有意义的在php代码中而不是控制台输出
【解决方案2】:

我认为问题在于您的 & 符号位置不太对。试试这个:

$logFile = 'app-output.txt';
$command = '(nohup /export/php -r "require \'/export/wiki.php\';update_wiki(1);"';
$command.= ' > "'.$logFile.'" 2>&1) &';
exec($command);

【讨论】:

    猜你喜欢
    • 2011-04-29
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    相关资源
    最近更新 更多