【问题标题】:Console output gets lost upon starting application as child process in C#在 C# 中将应用程序作为子进程启动时控制台输出丢失
【发布时间】:2021-11-09 14:22:08
【问题描述】:

我在 C# 中启动的进程出现问题,尽管它的输出被重定向,但它没有输出到控制台。

我正在一个 unityci docker 容器中运行一个控制台应用程序,它允许我以批处理模式启动 unity,并且应该向控制台输出一些东西。

如果我使用 bash 使用 unity-editor -projectPath myProject -executeMethod myMethod -logFile - 启动统一,我会按预期在控制台中显示所有输出。

如果我使用 C# 使用相同的参数启动 bash 进程,我不会得到任何输出。

这是我用来启动新进程的代码:

void StartProcess()
{
    string argsString = "-projectPath myPath -executeMethod myMethod -logFile -";
    ProcessStartInfo startInfo = new ProcessStartInfo(argsString)
    {
        FileName = "/bin/bash",
        Arguments = $"-c unity-editor \"{argsString}\"",
        RedirectStandardOutput = true,
        RedirectStandardError = false, 
        UseShellExecute = false,
        CreateNoWindow = true,
    };

    using Process proc = Process.Start(startInfo);
    OutputDataReceived += OnOutputDataReceived;            
    proc.BeginOutputReadLine();

    proc.WaitForExit();
}

void OnOutputDataReceived(object obj, DataReceivedEventArgs args)
{
    if(args.Data.StartsWith("[")
        Console.WriteLine(args.Data);
}

unity-editor 命令是我正在使用的 unityci docker 容器的一部分。它执行以下操作:

#!/bin/bash

if [ -d /usr/bin/unity-editor.d ] ; then
  for i in /usr/bin/unity-editor.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
fi

xvfb-run -ae /dev/stdout "$UNITY_PATH/Editor/Unity" -batchmode "$@"

所以最后我有一个控制台应用程序,它运行一个启动另一个应用程序的可执行文件,而控制台输出在两者之间的某个地方丢失了。 有人能解释一下输出的去向以及如何让它在控制台中显示吗?

【问题讨论】:

标签: c# linux bash docker


【解决方案1】:

我想通了。问题是我是如何开始这个过程的。 而不是启动一个 bash 实例来运行这样的脚本:

ProcessStartInfo startInfo = new ProcessStartInfo("/bin/bash", $"-c unity-editor \"{argsString}\"");

我应该直接将脚本作为进程启动:

ProcessStartInfo startInfo = new ProcessStartInfo("unity-editor", argsString);

我的印象是,您不能直接将 bash 脚本作为进程启动,因为这会引发 System.ComponentModel.Win32Exception: Exec format error 异常,但是将 #!/bin/bash 作为脚本的第一行可以让它们毫无问题地运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 2017-11-18
    • 2016-03-07
    相关资源
    最近更新 更多