Search code examples
c#processpinvoke

Alternative native api for Process.Start


Ok this is not duplicate of "Alternative to Process.Start()" because my question is something different here.

I need to run a process and wait till execution of process and get the output of console.

There is way to set RedirectStandardOutput and RedirectStandardError to true, however this does not function well on some machines, (where .NET SDK is not installed), only .NET runtime is installed, now it works on some machines and doesnt work on some machines so we dont know where is the problem.

I have following code,

        ProcessStartInfo info = new ProcessStartInfo("myapp.exe", cmd);
        info.CreateNoWindow = true;
        info.UseShellExecute = false;
        info.RedirectStandardError = true;
        info.RedirectStandardOutput = true;
        Process p =  Process.Start(info);
        p.WaitForExit();
        Trace.WriteLine(p.StandardOutput.ReadToEnd());
        Trace.WriteLine(p.StandardError.ReadToEnd());

On some machines, this will hang forever on p.WaitForExit(), and one some machine it works correctly, the behaviour is so random and there is no clue.

Now if I can get a real good workaround for this using pinvoke, I will be very happy.

myapp.exe is nothing but writing 10 hello world statements on screen.


Solution

  • Ok I got this answer from somewhere...

        using System.Diagnostics;
        using System.Threading;
    
        ProcessStartInfo info = new ProcessStartInfo("myapp.exe", cmd); 
        info.CreateNoWindow = true; 
        info.UseShellExecute = false; 
        info.RedirectStandardError = true; 
        info.RedirectStandardOutput = true; 
        Process p =  new Process();
        p.StartInfo = info; 
        p.BeginOutputReadLine();
        p.BeginErrorReadLine();
    
        AutoResetEvent wait = new AutoResetEvent(false);
    
        p.Exited += (s,e)=>{
            wait.Set();
        }
        p.Start();
        wait.WaitOne();