I am trying to asynchronously get the the standard output of an .exe file, that I start from my C# program but the DataReceivedEventHandler is never called.
My C# code:
using System;
using System.Diagnostics;
namespace ExeRunner
{
class Program
{
static void Main(string[] args)
{
Process exeProcess;
exeProcess = new Process();
exeProcess.OutputDataReceived += new DataReceivedEventHandler(process_DataReceived);
exeProcess.StartInfo.FileName = "<Path of exe file>";
exeProcess.StartInfo.UseShellExecute = false;
exeProcess.StartInfo.RedirectStandardOutput = true;
exeProcess.Start();
exeProcess.BeginOutputReadLine();
exeProcess.WaitForExit(); //Alternatively leaving this out.
}
static public void process_DataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
}
}
While debugging i never actually get to the call of the method process_DataReceived.
The .exe file I have to read from, is a c++ program, that writes to the console with the method printf, and never exits. I can recreate the error with an executable file built out of the following c++ sources:
#include "stdafx.h"
#include "Windows.h"
#include <iostream>
int main(int argc, _TCHAR* argv[])
{
//setvbuf(stdout, NULL,_IOLBF,1024);
printf("x=%s\n", "sometext");
std::cout << "test\n";
printf("3453%s\n", "moretext");
printf("x=sd : %s\n", "evenmoretext");
//fflush(stdout);
Sleep(10000000);
printf("next test");
return 0;
}
If I comment in the fflush or set the buffer to 0 with setvbuf everything works fine. So the problem seems to be the buffer of stdout not flushing on a newline. At least not if the StandardOutput is redirected.
The thing is, I can not change the actual c++ program, whose executable I have to read from.
In my C# code: Is there a possibility set the stdout buffer of the c++ executable to 0, or force it to flush after encountering a new line?
If not can I still work around this problem in any way in the C# code?