首页 > 解决方案 > 抑制子进程的输出

问题描述

假设我们使用以下命令启动控制台应用程序:

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

这段代码导致 double StandardOutputand StandardError,因为父进程和子进程会将数据写入同一个终端。如何抑制子进程输出和/或分离子控制台?

当然我可以这样做:

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);
}

据我了解,这将一直有效,直到父进程还活着,但是如果子进程的工作时间比父进程长怎么办?需要一些稳定的跨平台解决方案。

标签: c#.netlinuxwindowsconsole

解决方案


推荐阅读