【发布时间】:2014-02-23 18:17:08
【问题描述】:
我目前正在编写一个程序,用作第二个控制台程序的接口,因此它应该读取该程序的输出,对其进行处理并根据需要发回命令。
当我在 Windows 机器上的 Visual Studio 中测试我的代码时,一切正常。但是当我在我的 Ubuntu 机器上使用 Mono (xbuild) 编译它时,我的程序无法读取控制台程序的输出(而且我没有收到任何异常或任何东西)
我的相关代码如下。在查看其他人的操作方式后,我还尝试使用ProcessStartInfo 参数以/bin/bash -c '/path/to/console_program' 运行控制台程序,但它给了我同样的静默结果。
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);
}
}
}
发现其中有什么明显的错误需要我修复以使其在 Linux 端运行?
【问题讨论】: