c# - 脚本完成后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
解决方案
我自己解决了。经过更多的挖掘,我意识到如果标准输出流变满,它将停止。所以最后我在处理过程中不断地读取流。我的最终代码看起来像这样并且完美运行:
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;
推荐阅读
- python - 从 DateTime 数据框列中提取时间并使用线图绘制每小时时间
- javascript - Howler.JS 从使用 vue 的方法播放时不播放音频
- google-apps-script - 为什么代码有时会从自身触发?
- javascript - 正则表达式匹配和分组直到一个字符序列
- python - 如何正确保存文件以避免 UnicodeDecodeError
- ios - iOS Build 在模拟器中工作,但在真实设备上存档和运行时抛出错误
- python-3.x - 如何解决Netlogo中使用python扩展的错误?
- python-3.x - 如何从 PYTHONPATH 上的目录中正确导入模块?
- javascript - 在 React Native 上使用 Ajax
- javascript - module.exports 的含义是什么?为什么叫模块?