【问题标题】:php exec() background process issuesphp exec() 后台进程问题
【发布时间】:2013-01-11 10:24:20
【问题描述】:

我正在尝试使用以下命令在后台处理文件,但它什么也没做。

exec("php csv.php $file $user > /dev/null &", $output);

如果我删除 > /dev/null &,则文件会处理,但不会在后台处理。

exec("php csv.php $file $user", $output);

有什么想法吗?

【问题讨论】:

  • 您是否尝试过使用 passthru 或 popen?我从未使用过 exec,但我确信它适用于它们。
  • 如果你希望它异步运行,你不应该期待输出。我也会在 exec 之前加上一个“@”

标签: php exec


【解决方案1】:

注意:

如果使用此函数启动程序,为了使其继续在后台运行,程序的输出必须重定向到文件或另一个输出流。否则会导致 PHP 挂起,直到程序执行结束。

http://php.net/manual/en/function.exec.php

所以:

exec("php csv.php $file $user > /dev/null &"); // no $output

【讨论】:

  • 他正在将输出重定向到 /dev/null
  • 此时不应提供第二个参数。
  • 所以不能在后台运行这个附加参数?
  • 我的坏 +1。您也许可以将 proc_open 与描述符一起使用。
  • 删除了第二个输入,当脚本立即停止时,实际的命令并没有运行。
【解决方案2】:

您考虑过使用屏幕吗?您可以启动在分离进程中运行的屏幕会话。输出将转到屏幕会话,您可以在它仍在运行时重新附加到另一个终端。

exec("screen -d -m -S my_php_session csv.php $file $user", $output);

【讨论】:

    【解决方案3】:

    除了Emery King's answer,您必须使用单个exec() 调用才能终止后台进程。一开始我的印象是,如果把进程放在后台,只要我有进程ID,我就可以继续愉快地杀了它,但事实并非如此。

    例如:

    // Runs the background process for 10 seconds
    // and then kills it and allows php to continue
    exec('sh -c \'echo $$ > pid; exec long_running_process\' > /dev/null 2>&1 & sleep 10 && kill $(cat pid)');
    
    // Runs the background process but does not allow
    // php to continue until the background process finishes.
    exec('sh -c \'echo $$ > pid; exec long_running_process\' > /dev/null 2>&1 &');
    exec(' sleep 10 && kill $(cat pid)'); // <- does not execute until background process is done (at which point pid is already dead)
    
    • echo $$ &gt; pidlong_running_process 的进程ID 写入名为pid 的文件中。

    • &gt; /dev/null 2&gt;&amp;1 &amp; 将 stdout 和 stderr 重定向到 /dev/null 并将 long_running_process 放入后台。

    • sleep 10 &amp;&amp; kill $(cat pid) 等待 10 秒,然后终止 ID 在 pid 文件中的进程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多