3

我在使用进程的重定向输入/输出时遇到了一些麻烦。最初,我有两个应用程序通过 tcp/ip 进行通信。服务器告诉客户端打开 cmd.exe,然后向客户端发出命令,客户端必须重定向到 cmd.exe 进程。然后客户端读取输出并将其发送回服务器。基本上我正在创建一种远程使用命令行的方法。

问题是它适用于第一个命令,然后什么都没有。我能够在不使用 tcp/ip 的情况下重新创建问题。

Process p = new Process();
ProcessStartInfo psI = new ProcessStartInfo("cmd");
psI.UseShellExecute = false;
psI.RedirectStandardInput = true;
psI.RedirectStandardOutput = true;
psI.CreateNoWindow = true;
p.StartInfo = psI;
p.Start();
p.StandardInput.AutoFlush = true;
p.StandardInput.WriteLine("dir");
char[] buffer = new char[10000];
int read = 0;
// Wait for process to write to output stream
Thread.Sleep(500);
while (p.StandardOutput.Peek() > 0)
{
    read += p.StandardOutput.Read(buffer, read, 10000);
}
Console.WriteLine(new string(buffer).Remove(read));

Console.WriteLine("--- Second Output ---");
p.StandardInput.WriteLine("dir");
buffer = new char[10000];
read = 0;
Thread.Sleep(500);
while (p.StandardOutput.Peek() > 0)
{
    read += p.StandardOutput.Read(buffer, read, 10000);
}
Console.WriteLine(new string(buffer).Remove(read));
Console.ReadLine();

这显然是丑陋的测试代码,但我得到了相同的结果。我可以第一次读取输出,然后第二次就空了。我猜当我第一次使用输出流时我会锁定它并阻止 cmd.exe 再次使用该流?如果这是真的,那么在每个输入命令之后多次使用输出流的正确方法是什么。我想同步执行此操作以保持命令行的感觉。如果唯一的解决方案是异步读取输出流,是否有一种方法可以概括地确定进程何时完成执行我的输入?我不希望服务器在第一个命令完成之前告诉客户端执行另一个命令。

谢谢。

4

1 回答 1

6

所有命令都必须是相同的 cmd 会话吗?怎么样:

    private static void RunCommand(string command)
    {
        var process = new Process()
                          {
                              StartInfo = new ProcessStartInfo("cmd")
                               {
                               UseShellExecute = false,
                               RedirectStandardInput = true,
                               RedirectStandardOutput = true,
                               CreateNoWindow = true,
                               Arguments = String.Format("/c \"{0}\"", command),
                               }
                          };
        process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
        process.Start();
        process.BeginOutputReadLine();

        process.WaitForExit();
    }
于 2010-11-08T08:55:54.333 回答