首页 > 解决方案 > 脚本完成后PHP进程不会退出

问题描述

我正在使用 C# 开发自定义网络服务器。我正在调用 php-chi.exe。我的代码如下:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
string sOutput = "";

proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = "php/php-cgi.exe";

proc.StartInfo.Arguments = "-f " + filePath + " " + queryString;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;

proc.Start();

StreamReader hOutput = proc.StandardOutput;

proc.WaitForExit(2000);

if (proc.HasExited)
            return hOutput.ReadToEnd();

return "Web Server attempted to call PHP, however the call has timedout. output = " +hOutput.ReadToEnd();

当我将一个低于特定大小的 php 文件传递​​给它时,这对我来说绝对没问题。但是如果 php 文件大于 4 或 5kb 左右,则 php 进程在完成时并没有结束,导致代码挂起,直到 2000ms 的超时。难道我做错了什么?超时输出返回我想要获取的完整 HTML。只是这个过程没有结束,它必须等待。

我一直在搜索谷歌大约一个小时,但我找不到它为什么这样做。

感谢您的帮助:D

标签: c#phpwebserver

解决方案


我自己解决了。经过更多的挖掘,我意识到如果标准输出流变满,它将停止。所以最后我在处理过程中不断地读取流。我的最终代码看起来像这样并且完美运行:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
string sOutput = "";

proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = "php/php-cgi.exe";

proc.StartInfo.Arguments = "-f " + filePath + " " + queryString;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;

proc.Start();

StreamReader hOutput = proc.StandardOutput;

Stopwatch timeout = new Stopwatch();
timeout.Start();

string buffer = "";
int timeoutMS = 2000;
while (timeout.ElapsedMilliseconds < timeoutMS)
{
    buffer += hOutput.ReadToEnd();
    if (proc.HasExited)
    {
        break;
    }
}
if (timeout.ElapsedMilliseconds >= timeoutMS)
{
    return "Web Server attempted to call PHP, however the call has timedout.";
}

return buffer;

推荐阅读