c# – PHP process not exiting once script is finished-ThrowExceptions

Exception or error:

I’m working on a custom webserver in C#. I’m calling the php-chi.exe. My code for this is as follows:

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();

This is working absolutely fine for me when I pass it a php file below a certain size. But if the php file is greater than about 4 or 5kb, the php process does not end when it’s finished, causing the code to hang until the timeout of 2000ms. Am I doing something wrong?
The output on timeout returns the full HTML that I’m trying to get. It’s just that the process isn’t ending and it has to wait.

I’ve been searching google for about an hour and I cannot find why it is doing this.

Thanks for your help 😀

How to solve:

I solved it myself. After some more digging, I realised that it will halt if the standardoutput stream becomes full. So in the end I continuously read the stream as it was processing. My final code looks like this and works perfectly:

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;

Leave a Reply

Your email address will not be published. Required fields are marked *