2010-12-10 17 views
1

我正在编写几个PHP脚本来执行程序,捕获它的STDOUT并在完成时捕获返回代码。这些程序可能会立即返回,或在20分钟内完成,因此我需要在完成时进行监控。在后台执行程序,并捕获返回代码(php和windows)

我找不到在后台启动程序并捕获[外部日志文件]返回代码的方法。如果我简单地使用exec或proc_open,我的php脚本就会被阻塞,当这个过程需要20分钟时,这是不好的。

即使我无法捕获返回码,我需要知道该过程何时完成。 (我可以把错误代码显示在输出代替)

我可以使用exec("start my.exe");,赶上STDOUT,但我不能让返回代码(还有不知道什么时候,它的完成)

我想过通过批处理文件exec(start my.bat);并在批处理文件中捕获返回代码,但我的命令行有动态选项,所以我宁愿做类似的事情;
exec("start cmd \"echo hello\");

编辑:但我还没有找到一种方法来在命令行上动态生成批处理命令列表。如果有人知道一种方法,我会非常感激。
cmd /C "echo hello"是解决这一

不需要跨平台,严格窗口(XP-7)

+0

你在做什么与返回代码?在网站上输出它? – 2010-12-10 11:17:41

+0

是的,我使用返回码来确定错误和下一个阶段。但它也可以告诉我这个过程已经完成。 – 2010-12-10 11:41:36

回答

0

好的,这是我到目前为止的地方。我想我不需要一个动态的批处理文件,我只能提供参数(杜)。 这样我就可以叫 exec("start Batch.bat log.txt stdout.txt c:\my.exe a b c"); ,并与一些AJAX监控日志文件(像现在这样)

REM first 2 params are log filenames 
set LogFilename=%1 
shift 
set StdOutFilename=%1 
shift 

REM Code to concatonate all following params from here 
REM http://stackoverflow.com/questions/761615/is-there-a-way-to-indicate-the-last-n-parameters-in-a-batch-file 
set params=%1 
:loop 
shift 
if [%1]==[] goto afterloop 
set params=%params% %1 
goto loop 
:afterloop 

REM command line is everything after the log-filename param 
set CommandLine=%params% 
@echo log: %LogFilename% 
@echo stdout: %StdOutFilename% 
@echo command: %CommandLine% 

if ["%LogFilename%"]==[]  exit 255; 
if ["%StdOutFilename%"]==[] exit 254; 
if ["%CommandLine%"]==[]  exit 253; 

REM execute command hidden(/B), wait for it to finish so we can get the return code (/WAIT) and output to stdlog 
@start /B /WAIT %CommandLine% >> %StdOutFilename% 

REM log return code "RET X" 
@echo RET %ERRORLEVEL% >> %LogFilename% 

,并且调用PHP代码;

$BatchCommandLine = "start /D $Cwd /B /WAIT execute.bat $LogName %StdLogName $Exe $Params"; 
$OutputLine = exec($BatchCommandLine, $Output, $ReturnCode); 
if ($ReturnCode != 0) 
echo "Batch file failed to execute"; 

* 编辑:*哎呀,EXEC()不会在后台甚至开始推出。仍然,解决了我的其他问题...

+0

很明显,应该是ERRORLEVEL而不是%ERRORLEVEL%http://blogs.msdn.com/b/oldnewthing/archive/2008/09/26/8965755.aspx – 2010-12-10 14:50:39

相关问题