views:

107

answers:

3

Ok this is not duplicate of "http://stackoverflow.com/questions/2065592/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.

+1  A: 

Could it be that your child process really hangs for ever, eg. waiting on input or displaying an error dialog that is not visible?

The native API is CreateProcess, and it's corresponding pInvoke.

Remus Rusanu
myapp.exe is nothing but writing 10 hello world statements on screen, CreateProcess is too complicated, I am unable to set all values correct so wanted to know if anyone has made good wrapper around CreateProcess that will be helpful.
Akash Kava
A: 

Using a separate work around by calling native code is not going to correct the problem. The Process API is just a thin wrapper around the native Process functions - using them directly is just going to make your code more confusing and cause other problems.

It sounds like the problem, in this case, is your "myapp.exe". For some reason, that application is not terminating on those machines. If you discover what is causing that, you will likely be able to make this work correctly using Process.Start.

Reed Copsey
myapp.exe is nothing but writing 10 hello world statements on screen.
Akash Kava
A: 

Ok I got this answer from somewhere...

    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.BeginReadStandardOutput();
    p.BeginReadStandardError();

    AutoResetEvent wait = new AutoResetEvent(false);

    p.Exit += (s,e)=>{
        wait.Set();
    }
    p.Start();
    wait.WaitOne();
Akash Kava