先进的PHP过程控制


advance process control in PHP

我需要构建一个用户将文件发送到服务器的系统然后PHP将使用system()运行命令行工具(示例tool.exe userfile)我需要一种方法来查看进程的pid,以了解已经启动该工具的用户还有一种方法可以知道工具何时停止。

这在Windows vista机器上是可能的吗?我无法移动到Linux服务器。

除了当用户关闭浏览器窗口时代码必须继续运行

与其试图获取进程的ID并监视它运行了多长时间,我认为你想做的是有一个"包装器"进程来处理预处理/后处理,比如日志记录或数据库操作。

的第一步是创建一个异步进程,它将独立于父进程运行,并允许它通过调用一个网页来启动。

在Windows上,我们使用WshShell:

$cmdToExecute = "tool.exe '"$userfile'"";
$WshShell = new COM("WScript.Shell"); 
$result = $WshShell->Run($cmdToExecute, 0, FALSE);

…并且(为了完整起见)如果我们想在*nix上执行,我们将> /dev/null 2>&1 &附加到命令:

$cmdToExecute = "/usr/bin/tool '"$userfile'"";
exec("$cmdToExecute > /dev/null 2>&1 &");

所以,现在你知道了如何启动一个外部进程,它不会阻塞你的脚本,并在你的脚本完成后继续执行。但这并不能完全说明问题——因为您想要跟踪外部进程的开始和结束时间。这很简单——我们只需将其封装在一个小PHP脚本中,我们将其命名为…

wrapper.php

<?php
  // Fetch the arguments we need to pass on to the external tool
  $userfile = $argv[1];
  // Do any necessary pre-processing of the file here
  $startTime = microtime(TRUE);
  // Execute the external program
  exec("C:/path/to/tool.exe '"$userfile'"");
  // By the time we get here, the external tool has finished - because
  // we know that a standard call to exec() will block until the called
  // process finishes
  $endTime = microtime(TRUE);
  // Log the times etc and do any post processing here

因此,我们不直接执行该工具,而是在主脚本中执行命令:

$cmdToExecute = "php wrapper.php '"$userfile'"";

…对于你想做的事情,我们应该有一个精细可控的解决方案。

注意:不要忘记在必要的地方添加escapeshellarg() !