在后台执行程序,并捕获返回代码(php& windows)

时间:2010-12-10 11:16:24

标签: php windows batch-file

我正在编写几个PHP脚本来执行程序,捕获它的STDOUT并在完成后捕获返回代码。这些程序可以立即返回,或者在20分钟内完成,所以我需要监控它们何时完成。

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

即使我无法捕获返回代码,我也需要知道进程何时完成。 (我可以在STDOUT中输入错误代码)

我可以使用exec("start my.exe");并捕获STDOUT,但我无法获取返回码(也不知道它何时完成)

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

编辑:但是我找不到在命令行上动态创建批处理命令列表的方法。如果有人知道一种方法我会非常感激。
cmd /C "echo hello"是此

的解决方案

不需要跨平台,严格来说是windows(xp-7)

2 个答案:

答案 0 :(得分:1)

看看这个:Executing background processes from PHP on Windows。它解释了一些可能性。

答案 1 :(得分:0)

好的,这是我到目前为止所处的地方。我想我不需要动态批处理文件,我只能提供args(duh)。 所以我可以打电话 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()也不会在后台启动。仍然,解决了我的其他问题...