【问题标题】:capture process stdout and stderr in the correct ordering以正确的顺序捕获进程 stdout 和 stderr
【发布时间】:2013-09-02 23:48:04
【问题描述】:

我从 C# 启动一个进程,如下所示:

public bool Execute()
{
    ProcessStartInfo startInfo = new ProcessStartInfo();

    startInfo.Arguments =  "the command";
    startInfo.FileName = "C:\\MyApp.exe";

    startInfo.UseShellExecute = false;
    startInfo.RedirectStandardOutput = true;
    startInfo.RedirectStandardError = true;

    Log.LogMessage("{0} {1}", startInfo.FileName, startInfo.Arguments);

    using (Process myProcess = Process.Start(startInfo))
    {
        StringBuilder output = new StringBuilder();
        myProcess.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e)
        {
            Log.LogMessage(Thread.CurrentThread.ManagedThreadId.ToString() + e.Data);
        };
        myProcess.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e)
        {
            Log.LogError(Thread.CurrentThread.ManagedThreadId.ToString() +  " " + e.Data);            
        };

        myProcess.BeginErrorReadLine();
        myProcess.BeginOutputReadLine();

        myProcess.WaitForExit();

    }

    return false;
}

但这有一个问题......如果有问题的应用程序按此顺序写入std out和std err:

std out: msg 1
std err: msg 2
std out: msg 3

那么我从日志中看到的输出是:

msg 2
msg 1
msg 3

这似乎是因为事件处理程序是在另一个线程中执行的。所以我的问题是如何维护写入 std err 和 std out 的过程顺序?

我曾想过使用时间戳,但由于线程的抢占性,我认为这不会起作用..

更新:确认在数据上使用时间戳是没有用的。

最终更新:接受的答案解决了这个问题 - 但是它确实有一个缺点,当流合并时,无法知道写入哪个流。因此,如果您需要写入 stderr == 失败的逻辑而不是应用程序退出代码,您可能仍然会被搞砸。

【问题讨论】:

  • 作为一个建议,您是否尝试过更改BeginErrorReadLineBeginOutputReadLine 呼叫的顺序?
  • 查看接受的答案,这根本没有帮助

标签: c# multithreading stdout stderr


【解决方案1】:

虽然我很欣赏 Erti-Chris 的回答(那是什么,Pascal?),但我认为其他人可能更喜欢托管语言的答案。此外,对于那些说“你不应该这样做”的批评者,因为 STDOUT 和 STDERR 不能保证保持顺序:是的,我理解,但有时我们必须与程序(我们没有编写)进行互操作期望我们这样做,正确的语义该死。

这是一个 C# 版本。它没有通过调用CreateProcess 来绕过托管的Process API,而是使用另一种方法将STDERR 重定向到Windows shell 中的STDOUT 流。因为UseShellExecute = true 实际上并没有使用cmd.exe shell(惊喜!),所以您通常不能使用shell 重定向。解决方法是自己启动cmd.exe shell,手动输入我们真正的 shell 程序和参数。

请注意,以下解决方案假定您的 args 数组已正确转义。我喜欢使用内核的GetShortPathName 调用的蛮力解决方案,但您应该知道它并不总是适合使用(例如,如果您不在 NTFS 上)。此外,您确实想要执行异步读取 STDOUT 缓冲区的额外步骤(如下所示),因为如果您不这样做,your program may deadlock

using System;
using System.Diagnostics;
using System.Text;
using System.Threading;

public static string runCommand(string cpath, string[] args)
{
    using (var p = new Process())
    {
        // notice that we're using the Windows shell here and the unix-y 2>&1
        p.StartInfo.FileName = @"c:\windows\system32\cmd.exe";
        p.StartInfo.Arguments = "/c \"" + cpath + " " + String.Join(" ", args) + "\" 2>&1";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;

        var output = new StringBuilder();

        using (var outputWaitHandle = new AutoResetEvent(false))
        {
            p.OutputDataReceived += (sender, e) =>
            {
                // attach event handler
                if (e.Data == null)
                {
                    outputWaitHandle.Set();
                }
                else
                {
                    output.AppendLine(e.Data);
                }
            };

            // start process
            p.Start();

            // begin async read
            p.BeginOutputReadLine();

            // wait for process to terminate
            p.WaitForExit();

            // wait on handle
            outputWaitHandle.WaitOne();

            // check exit code
            if (p.ExitCode == 0)
            {
                return output.ToString();
            }
            else
            {
                throw new Exception("Something bad happened");
            }
        }
    }
}

【讨论】:

  • 谢谢,这实际上是一个非常简单的方法。在我的情况下,我的过程恰好是一个批处理文件,所以这确实不会产生额外的开销或复杂性。
  • 澄清一下,AutoResetEvente.Data == null 存在是因为 p.WaitForExit 可能发生在最后一个 OutputDataReceived 事件之前。但是当输出流关闭时,会发送带有e.Data == null 的最终事件。来源:msdn.microsoft.com/en-us/library/…
【解决方案2】:

据我了解,您希望保留 stdout/stderr 消息的顺序。我没有看到任何体面的方式来使用 C# 托管进程来做到这一点(反射 - 是的,讨厌的子类化黑客攻击 - 是的)。看起来它几乎是硬编码的。

此功能不依赖于线程本身。如果要保持顺序,STDOUTSTDERROR 必须使用相同的句柄(缓冲区)。如果他们使用相同的缓冲区,它将被同步。

这是来自 Process.cs 的 sn-p:

 if (startInfo.RedirectStandardOutput) {
    CreatePipe(out standardOutputReadPipeHandle, 
               out startupInfo.hStdOutput, 
               false);
    } else {
    startupInfo.hStdOutput = new SafeFileHandle(
         NativeMethods.GetStdHandle(
                         NativeMethods.STD_OUTPUT_HANDLE), 
                         false);
}

if (startInfo.RedirectStandardError) {
    CreatePipe(out standardErrorReadPipeHandle, 
               out startupInfo.hStdError, 
               false);
    } else {
    startupInfo.hStdError = new SafeFileHandle(
         NativeMethods.GetStdHandle(
                         NativeMethods.STD_ERROR_HANDLE),
                         false);
}

如你所见,会有两个缓冲区,如果我们有两个缓冲区,我们已经丢失了订单信息。

基本上,您需要创建自己的 Process() 类来处理这种情况。伤心?是的。 好消息是它并不难,看起来很简单。这是取自 StackOverflow 的代码,不是 C#,但足以理解算法:

function StartProcessWithRedirectedOutput(const ACommandLine: string; const AOutputFile: string;
  AShowWindow: boolean = True; AWaitForFinish: boolean = False): Integer;
var
  CommandLine: string;
  StartupInfo: TStartupInfo;
  ProcessInformation: TProcessInformation;
  StdOutFileHandle: THandle;
begin
  Result := 0;

  StdOutFileHandle := CreateFile(PChar(AOutputFile), GENERIC_WRITE, FILE_SHARE_READ, nil, CREATE_ALWAYS,
    FILE_ATTRIBUTE_NORMAL, 0);
  Win32Check(StdOutFileHandle <> INVALID_HANDLE_VALUE);
  try
    Win32Check(SetHandleInformation(StdOutFileHandle, HANDLE_FLAG_INHERIT, 1));
    FillChar(StartupInfo, SizeOf(TStartupInfo), 0);
    FillChar(ProcessInformation, SizeOf(TProcessInformation), 0);

    StartupInfo.cb := SizeOf(TStartupInfo);
    StartupInfo.dwFlags := StartupInfo.dwFlags or STARTF_USESTDHANDLES;
    StartupInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE);
    StartupInfo.hStdOutput := StdOutFileHandle;
    StartupInfo.hStdError := StdOutFileHandle;

    if not(AShowWindow) then
    begin
      StartupInfo.dwFlags := StartupInfo.dwFlags or STARTF_USESHOWWINDOW;
      StartupInfo.wShowWindow := SW_HIDE;
    end;

    CommandLine := ACommandLine;
    UniqueString(CommandLine);

    Win32Check(CreateProcess(nil, PChar(CommandLine), nil, nil, True,
      CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInformation));

    try
      Result := ProcessInformation.dwProcessId;

      if AWaitForFinish then
        WaitForSingleObject(ProcessInformation.hProcess, INFINITE);

    finally
      CloseHandle(ProcessInformation.hProcess);
      CloseHandle(ProcessInformation.hThread);
    end;

  finally
    CloseHandle(StdOutFileHandle);
  end;
end;

来源:How to redirect large amount of output from command executed by CreateProcess?

您想使用 CreatePipe 而不是文件。从管道中,您可以像这样异步读取:

standardOutput = new StreamReader(new FileStream(
                       standardOutputReadPipeHandle, 
                       FileAccess.Read, 
                       4096, 
                       false),
                 enc, 
                 true, 
                 4096);

和 BeginReadOutput()

  if (output == null) {
        Stream s = standardOutput.BaseStream;
        output = new AsyncStreamReader(this, s, 
          new UserCallBack(this.OutputReadNotifyUser), 
             standardOutput.CurrentEncoding);
    }
    output.BeginReadLine();

【讨论】:

  • 是的,我同意这个答案。今天下午我对这个问题做了很多研究,我认为这是获得它的正确方法。即使您要使用 Process 上为 stdout/err 提供的底层 StreamReaders,它听起来也像 Peek 方法块,因为它在后台不使用 PeekNamedPipe。说了这么多,我一直在想你到底需要做什么。如果您只关心以正确的顺序捕获 stdout/stderr,而不关心哪个是哪个,您可能会创建一个批处理文件,该文件使用 2>&1 技巧将所有内容推送到 stdout。这行得通吗?
  • 理想情况下,我希望能够同时获得stdout(用于输出处理)和stdout+stderr(用于错误报告)。也许,钩子以某种方式用一个公共锁写入 2 个句柄......
  • 在我的情况下,使用带有 2>&1 的批处理文件也会以错误的顺序捕获它,我只是认为这根本不可能
  • @paulm:我认为 2>&1 行不通。刚刚在我的 .NET 应用程序上对其进行了测试,并比较了 GetStdHandle(STD_OUPUT) 和 GetStdHandle(STD_ERROR)。不确定批处理管道重定向是如何工作的,但是如果您调试,您会发现它不会使 2 个句柄相同。尝试重写 Pascal 代码,它应该适合你,paulm。
  • STDOUT/STDERR 从来都不是要订购的。据我现在所见:你要么得到一个,要么得到另一个。如果您可以两次运行相同的进程(一个用于 stdout,另一个用于 stdout/stderr),那么您会没事的。你可以做什么:下载 ApiMonitor 并查看控制台写入是如何在后台实现的(WriteOut)。您可以进行进程劫持,这将允许您拦截正在进行的任何呼叫 - 从而允许您做任何您想做的事情。请参阅 Google 中的 IAT API 挂钩 - 这不是一种可爱的方式,但它会起作用。
猜你喜欢
  • 2018-10-31
  • 2020-06-23
  • 2014-08-05
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
  • 1970-01-01
  • 2010-12-05
  • 2021-03-11
相关资源
最近更新 更多