Cmd.exe input / output redirection

I am having problems using the redirected I / O process. Initially, I had two applications communicating over tcp / ip. The server tells the client to open cmd.exe, and then gives the client commands that the client should redirect to the cmd.exe process. The client then reads the output and sends it back to the server. Basically, I created a way to remotely use the command line.

The problem is that it works for the first team, and then nothing will happen. I was able to recreate the problem without using 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 ? , . , . , , , ? , .

.

+3
1

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();
    }
+5

Source: https://habr.com/ru/post/1773458/


All Articles