Reputation: 359
I'm currently writing a program that is used as an interface for a second console program, so it should read that program's output, treat it and send back commands as needed.
When I test my code in Visual Studio on Windows machine, everything works fine. But when I compile it with Mono (xbuild) on my Ubuntu machine, my program isn't able to read the output from the console program (and I'm not getting any exceptions or anything)
My relevant code is the following. I also tried running the console program as /bin/bash -c '/path/to/console_program'
with the ProcessStartInfo
arguments after seeing how some other people were doing it, but it gave me the same silent result.
private static ProcessStartInfo startInfo;
private static Process process;
private static Thread listenThread;
private delegate void Receive(string message);
private static event Receive OnReceive;
private static StreamWriter writer;
private static StreamReader reader;
private static StreamReader errorReader;
public static void Start(bool isWindows)
{
if(isWindows)
startInfo = new ProcessStartInfo("console_program.exe", "");
else
startInfo = new ProcessStartInfo("/path/to/console_program", "");
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.ErrorDialog = false;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
process = new Process();
process.StartInfo = startInfo;
bool processStarted = process.Start();
Console.WriteLine("[LOG] Engine started: " + processStarted.ToString());
writer = process.StandardInput;
reader = process.StandardOutput;
errorReader = process.StandardError;
OnReceive += new Receive(Engine_OnReceive);
listenThread = new Thread(new ThreadStart(Listen));
listenThread.Start();
}
private static void Engine_OnReceive(string message)
{
Console.WriteLine(message);
}
private static void Listen()
{
while (process.Responding)
{
string message = reader.ReadLine();
if (message != null)
{
OnReceive(message);
}
}
}
Seeing any obvious mistakes in there that I should fix to get it working on the Linux side?
Upvotes: 0
Views: 1343
Reputation: 58762
You should not use process.Responding
. Instead, use the null
check to detect end of stream. This makes sense to me even without knowing that mono always returns false
for the Responding
property (see mono source code) because the output from a terminated (not responding) process may still be buffered.
Upvotes: 1