Alternative native api for Process.Start

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

I need to start a process and wait for the process to complete and get console output.

There is a way to set RedirectStandardOutput and RedirectStandardError to true, however this doesn't work well on some machines (where the .NET SDK is not installed), only the .NET environment is installed, now it works on some machines and doesn't work on some machines, so we don't know where the problem is.

I have the 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 on p.WaitForExit () forever and one of them works correctly, the behavior is so random and there is no clue.

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

myapp.exe is nothing more than writing 10 screen greetings.

+2


a source to share


3 answers


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

      

0


a source


Maybe your child process really hangs forever, for example. waiting on input, or showing an error dialog that is not displayed?



The native CreateProcess API and it conforms to pInvoke .

+1


a source


Using a separate job by calling your own code will not fix the problem. The Process API is just a thin wrapper around the built-in Process Functions - using them directly will just make your code more confusing and cause other problems.

It looks like the problem in this case is your "myapp.exe". For some reason, this app doesn't end on these machines. If you find what is causing this, you can probably get the job done correctly with Process.Start.

0


a source







All Articles