作者:路路 | 来源:互联网 | 2023-01-26 19:21
我需要为交互式命令行程序编写一个包装器.
这意味着我需要能够通过其标准输入向其他程序发送命令,并通过其标准输出接收响应.
问题是,当输入流仍处于打开状态时,标准输出流似乎被阻止.一旦我关闭输入流,我就得到响应.但后来我无法发送更多命令.
这就是我目前使用的(主要来自这里):
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
.
有没有办法以全双工的方式与其他进程通信?