0

I need to control a console application written in C++ from C# app. The C# app can't read anything from output of C++ app. The application freezes when using the function process.StandardOutput.ReadLine(). I tried to create simple console apps in C#, C++ only with printf("Test sample\r\n") and Console.WriteLine("Test sample"). And the sample C# app works great, C++ not. So I don't know where I'm making a mistake. Probably C++ app writes bad end of line but I don't know how to solve it.

A code sample of main app in C# which controls another app written in C++ or C#.

            process= new Process()
            {
                StartInfo = new ProcessStartInfo(@"testApp")
                {
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = false,
                    WindowStyle = ProcessWindowStyle.Hidden
                }
            };

            process.Start();                
            inputWriter = process.StandardInput;                
            string text =process.StandardOutput.ReadLine();//C++ app freezes here    

And two test applications

In C++

int main(){
while (true) {
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    printf("Test send data\r\n");               

}
return 0;}

In C#

static void Main(string[] args)
    {
        while (true)
        {
            Thread.Sleep(500);
            Console.WriteLine("Test send data");
        }
    }
Filip Procházka
  • 187
  • 4
  • 13
  • Just to test, what if you in the C++ program wrote a newline like plain `"\n"`? Without the carriage-return (which should be added automatically by the underlying library code)? – Some programmer dude Jun 08 '17 at 10:59
  • I tried it but It's same problem. – Filip Procházka Jun 08 '17 at 11:01
  • Your C++ app automatically puts stdout in buffered mode when its output is redirected. That buffer doesn't get flushed and its content made available to your C# app until it fills up or stdout is closed. That is going to take quite a while when you sleep that much, at least a minute or two. Use fflush() or std::flush. – Hans Passant Jun 08 '17 at 12:19
  • @HansPassant Thank you for your help. It works great! :) – Filip Procházka Jun 09 '17 at 17:49

1 Answers1

0

Take a look at these answers: ProcessStartInfo hanging on "WaitForExit"? Why? and StandardOutput.ReadLine() hang the application using c#, they may both provide an explanation and a solution.

I have also tried to use ReadLineAsync:

while ((line = await process.StandardOutput.ReadLineAsync()) != null)
    Console.WriteLine(line);

and it worked. Note that if you chose this solution, you will have to make some changes in your code to make it async (you can wrap it in a task as well, it all depends on your need).

Eylon
  • 51
  • 3