C#实现在cmd正在运行process1时通过cmd再执行process2并返回process2的输出
时间: 2024-10-28 09:11:51 浏览: 25
在C#中,如果你想在`Process1`已经在CMD中运行的同时,异步执行`Process2`并接收其输出,你可以使用`Process`类的`Start()`方法结合`StreamReader`来读取每个进程的输出。下面是一个示例:
```csharp
using System;
using System.Diagnostics;
using System.IO.Pipes;
using System.Threading.Tasks;
public async Task<string> RunProcessesSequentially(string process1Command, string process2Command)
{
// 创建命名管道,用于进程间通信
var pipeName = "__your_unique_pipe_name__";
using (var serverPipe = new NamedPipeServerStream(pipeName, PipeDirection.Out))
{
// Start Process1 and redirect its output to the named pipe
ProcessStartInfo psi1 = new ProcessStartInfo("cmd.exe", $"/c {process1Command} > {pipeName}");
Process proc1 = new Process();
proc1.StartInfo = psi1;
proc1.Start();
// Wait for Process1 to finish writing to the pipe
proc1.WaitForExit();
// Start Process2, read its output from the same pipe
ProcessStartInfo psi2 = new ProcessStartInfo("cmd.exe", $"@echo off < {pipeName} && echo Process2 Output");
psi2.RedirectStandardInput = true;
psi2.RedirectStandardOutput = true;
Process proc2 = new Process();
proc2.StartInfo = psi2;
await proc2.StandardOutput.ReadToEndAsync();
return proc2.StandardOutput.ReadToEnd();
}
}
// 调用函数,获取并打印Process2的输出
public static void Main()
{
string command1 = "你的命令1";
string command2 = "你的命令2";
Console.WriteLine(RunProcessesSequentially(command1, command2));
}
```
在这个示例中,我们首先启动`Process1`并将它的输出重定向到一个命名管道。然后,`Process2`会从该管道读取输入,并将输出发送回标准输出。
阅读全文