C# .NET5/Core下的Linux进程输出重定向会导致错误/中断行为

C# .NET5/Core下的Linux进程输出重定向会导致错误/中断行为,c#,.net,linux,C#,.net,Linux,我有一个非常简单的.NET5 Linux程序(与Core 3.1上的行为相同),它运行Nano并等待它终止。如果我只重定向一个输出流,那么这段代码将按预期工作。如果Nano是通过Bash启动的,我可以和它进行精确的交互 现在,如果我重定向stderr和stdout,会发生一些奇怪的事情: nano窗口不会填充整个终端 转义序列显示在屏幕^X上作为示例 我可以使用菜单,但我必须按escape序列,然后按enter键 据我所知,stdout和stderr是不同的流,为什么它们会导致这些问题?如果

我有一个非常简单的.NET5 Linux程序(与Core 3.1上的行为相同),它运行Nano并等待它终止。如果我只重定向一个输出流,那么这段代码将按预期工作。如果Nano是通过Bash启动的,我可以和它进行精确的交互

现在,如果我重定向stderr和stdout,会发生一些奇怪的事情:

  • nano窗口不会填充整个终端
  • 转义序列显示在屏幕^X上作为示例
  • 我可以使用菜单,但我必须按escape序列,然后按enter键
据我所知,stdout和stderr是不同的流,为什么它们会导致这些问题?如果我跑步:

nano 2>> stderr.txt
我可以看到nano根本不生产stderr,而且一切都按预期工作

我更新了代码,只重定向stderr,一切正常。因此,这个问题与重定向两个输出流有关。代码已经在WSL1、WSL2和真实机器下运行

有效的代码:

static async Task Main(string[] args)
{
    var proc = new Process();
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.FileName = "/bin/nano";
    proc.StartInfo.Arguments = "hello";
    proc.StartInfo.CreateNoWindow = true;
    proc.StartInfo.RedirectStandardError = false;
    proc.StartInfo.RedirectStandardOutput = true; // only redirect stdout
    proc.StartInfo.RedirectStandardInput = false;

    proc.Start();

    var t1 = proc.StandardOutput.BaseStream.CopyToAsync(Console.OpenStandardOutput());
    proc.WaitForExit();
    await t1;
}
不符合以下条件的代码:

static async Task Main(string[] args)
{
    var proc = new Process();
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.FileName = "/bin/nano";
    proc.StartInfo.Arguments = "hello";
    proc.StartInfo.CreateNoWindow = true;
    proc.StartInfo.RedirectStandardError = true;
    proc.StartInfo.RedirectStandardOutput = true;
    proc.StartInfo.RedirectStandardInput = false;

    proc.Start();

    var t1 = proc.StandardOutput.BaseStream.CopyToAsync(Console.OpenStandardOutput());
    var t2 = proc.StandardError.BaseStream.CopyToAsync(Console.OpenStandardError());

    proc.WaitForExit();

    await t1;
    await t2;
}

我用nano作为一个很好的例子。实际程序的工作方式非常相似,但在输出时会产生stderr。

我不知道其机制,但我猜重定向这两种方式都会干扰进程,但进程会检测终端类型和窗口大小。所以我不知道你想要什么是可能的。Rup说的有意义,没有意义的是重定向一个Shell UI类型的应用程序的标准输出-当然UI需要在屏幕上运行?您是否正在制作一个在中间插入一些监控或录音的应用程序?