Search code examples
c#jscriptwsh

Why script hangs the host process when buffer size increases to 4MB?


We have added Process class to execute a script. Main method of the script file is defined in the next section. When Script executed the WaitForExit() method of Process class returns false every time .

Code Snippet:

public void ExecuteTheScript()
{
.......
  
try  
  {
        System.Diagnostics.Process pProc = new System.Diagnostics.Process();
        pProc.StartInfo.FileName = scriptPath;
        pProc.StartInfo.Arguments = scriptArguments;
        pProc.StartInfo.UseShellExecute = false;
        pProc.StartInfo.RedirectStandardOutput = true;
        pProc.StartInfo.RedirectStandardError = true;
        pProc.StartInfo.WorkingDirectory = Path.GetDirectoryName(scriptPath);        
        pProc.Start();
        DateTime startTime = pProc.StartTime;
    
        bool bHasExited = pProc.WaitForExit(120 * 1000);               
    
        int timeElapsed = (int)(DateTime.Now - startTime).TotalSeconds;
        if (timeElapsed >= timeoutInSeconds && !bHasExited)
         {
             if (sError == null)
                 sError = "timeout and not Exited Properly"
             if (!pProc.HasExited)
                 pProc.Kill();
             bOk = false;
         }
         _stdOut = pProc.StandardOutput.ReadToEnd();
         _stdErr = pProc.StandardError.ReadToEnd();
          if (pProcess.ExitCode != 0)
           {
               if (sError == null)
                  sError = pProc.ExitCode.ToString();
               bOk = false;
            }
   }
   catch (Exception e)
   {   
       if (sError == null)
         sError = e.message;
       bOk = false;
    }
}

We are using Cscript to execute the script file.

function main
{
    var i;
    var exit_Code = 0;
    var str = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" ;
    
    for (i = 1; i <= 51; i++) {
        WScript.Echo(str);
    }
    WScript.Quit(0);
}

Solution

  • From msdn:

    The code example avoids a deadlock condition by calling p.StandardOutput.ReadToEnd before p.WaitForExit. A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardOutput.ReadToEnd and the child process writes enough text to fill the redirected stream. The parent process would wait indefinitely for the child process to exit. The child process would wait indefinitely for the parent to read from the full StandardOutput stream.