3

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?

  • `std::endl` outputs a newline and flushes. – πάντα ῥεῖ Jun 24 '15 at 11:09
  • 1
    From what I know of C# there is nothing you can do as it is waiting for something to get into the buffer and nothing will until the C++ program flushes the output. If you are using Linux there are some things you could try [here](http://stackoverflow.com/questions/2055918/forcing-a-program-to-flush-its-standard-output-when-redirected) – NathanOliver Jun 24 '15 at 12:13

0 Answers0