views:

51

answers:

2

I have a console based c app . I am executing it from c# silently using Redirecting Standard Output and doing it synchronously which works fine. Now i want to do it in asynch manner which is giving output like synch manner. i.e OutPutDataRecieved event is fired but only after the console app(exe) finishes.OutputDataRecieved event is fired for each line after finish, not instantly as soon as it gets a line in output.

The code for asynch works for CMD.exe etc ,So,I am sure its c based app having problem in output. FYI:The output in c console is done using printf. Based on my findings: I think c console app is not giving output/writing to stdout until it finishes its execution. I tried setting buffer to null or flushing after every printf but none works.

Any tricks??

A: 

You can disable the buffering using setvbuf.

Here is a quick example, if you remove the call to setvbuf then the redirected content is only written once you press enter (waiting on the getchar()). With the setvbuf, the string is written to the redirected stream directly.

int _tmain(int argc, _TCHAR* argv[])
{
  setvbuf(stdout, NULL,_IONBF, 0);
  printf("Hello");
  getchar();
  return 0;
}
Chris Taylor
+1  A: 

Hey Chris, Thanks man.That worked like a charm.

I was using setbuf to set buffer null.

Really appreciate efforts of all you guyz.

FOr info of other guyz,this was my c# code which is available on internet forums and SO too.

        string command = @"Output.exe"; 
  string arguments = "hellotext"; 

  ProcessStartInfo info = new ProcessStartInfo(command, arguments); 

  // Redirect the standard output of the process.  
  info.RedirectStandardOutput = true; 
  info.RedirectStandardError = true; 

  // Set UseShellExecute to false for redirection 
  info.UseShellExecute = false; 

  Process proc = new Process(); 
  proc.StartInfo = info; 
  proc.EnableRaisingEvents = true; 

  // Set our event handler to asynchronously read the sort output. 
  proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived); 
  proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived); 
  proc.Exited += new EventHandler(proc_Exited); 

  proc.Start(); 
  // Start the asynchronous read of the sort output stream. Note this line! 
  proc.BeginOutputReadLine(); 
  proc.BeginErrorReadLine(); 

  proc.WaitForExit(); 

  Console.WriteLine("Exited (Main)"); 

} 

static void proc_Exited(object sender, EventArgs e) 
{ 

  Console.WriteLine("Exited (Event)"); 
} 



static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e) 
{ 
  Console.WriteLine("Error: {0}", e.Data); 
} 



static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e) 
{ 
  Console.WriteLine("Output data: {0}", e.Data); 
} 
@user445066, I am glad that helped.
Chris Taylor