C# 抑制子进程的输出
假设我们以以下方式启动控制台应用程序:C# 抑制子进程的输出,c#,.net,linux,windows,console,C#,.net,Linux,Windows,Console,假设我们以以下方式启动控制台应用程序: public static void StartProcess() { using var next = new Process(); next.StartInfo.UseShellExecute = false; next.StartInfo.FileName = "dotnet"; next.StartInfo.Arguments = "/opt/ConsoleApp1/ConsoleApp
public static void StartProcess()
{
using var next = new Process();
next.StartInfo.UseShellExecute = false;
next.StartInfo.FileName = "dotnet";
next.StartInfo.Arguments = "/opt/ConsoleApp1/ConsoleApp1.dll";
next.Start();
}
此代码导致双重标准输出
和标准错误
,因为父进程和子进程将数据写入同一终端。如何抑制子进程输出和/或分离子控制台
当然,我可以这样做:
public static void StartProcess()
{
using var next = new Process();
next.StartInfo.UseShellExecute = false;
next.StartInfo.FileName = "dotnet";
next.StartInfo.Arguments = "/opt/ConsoleApp1/ConsoleApp1.dll";
next.StartInfo.RedirectStandardOutput = true;
next.StartInfo.RedirectStandardError = true;
next.Start();
next.StandardOutput.BaseStream.CopyToAsync(Stream.Null);
next.StandardError.BaseStream.CopyToAsync(Stream.Null);
}
据我所知,在父进程处于活动状态之前,这将一直有效,但若子进程的工作时间比父进程长呢?需要一些稳定的跨平台解决方案。一般来说,生成
$SHELL“command>nul”
就可以了。这是所有常用SHELL都共享的语法。@BenVoigt,我想问的是如何用纯C#SoSystem.Environment.GetEnvironmentVariable(“SHELL”)
以编程方式跨平台执行此操作?