我需要为交互式命令行程序编写包装程序。如何从另一个.NET程序使用交互式命令行程序
这意味着我需要能够通过其标准输入发送命令到其他程序,并通过其标准输出接收响应。
问题是,当输入流仍然打开时,标准输出流似乎被阻塞。只要我关闭输入流,我就会得到响应。但后来我无法发送更多命令。
这是我在用的那一刻(主要来自here):
void Main() {
Process process;
process = new Process();
process.StartInfo.FileName = "atprogram.exe";
process.StartInfo.Arguments = "interactive";
// Set UseShellExecute to false for redirection.
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
// Redirect the standard output of the command.
// This stream is read asynchronously using an event handler.
process.StartInfo.RedirectStandardOutput = true;
// Set our event handler to asynchronously read the output.
process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
// Redirect standard input as well. This stream is used synchronously.
process.StartInfo.RedirectStandardInput = true;
process.Start();
// Start the asynchronous read of the output stream.
process.BeginOutputReadLine();
String inputText;
do
{
inputText = Console.ReadLine();
if (inputText == "q")
{
process.StandardInput.Close(); // After this line the output stream unblocks
Console.ReadLine();
return;
}
else if (!String.IsNullOrEmpty(inputText))
{
process.StandardInput.WriteLine(inputText);
}
}
}
我也尝试同步读取标准输出流,但具有相同的结果。任何方法无限期调用输出流块,直到输入流被关闭 - 即使是Peek()
和EndOfStream
。
有什么办法以全双工方式与其他进程通信?
你可以使异步线程? –
@BenderBending是的,我可以,但这会有帮助吗? – Karsten
我相信会的。 t一个线程上的输入流和另一个线程上的输出流。 –