【问题标题】:Process created by Process.Start() terminates when the parent application is closedProcess.Start() 创建的进程在父应用程序关闭时终止
【发布时间】:2011-12-22 20:10:29
【问题描述】:

我在 Debian 6 上使用 C# 和 Mono 2.10.2。

所以场景是我使用 Process.Start() 创建了一个流程,如下所示:

Process p = new Process();

p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.WorkingDirectory = "/home/lucy/";
p.StartInfo.FileName = "/bin/sh";
p.StartInfo.Arguments = "/home/lucy/test.sh";

p.EnableRaisingEvents = true;
p.ErrorDataReceived += new DataReceivedEventHandler(ShellProc_ErrorDataReceived);

p.Start();

在这种情况下称为 test.sh 的 shell 脚本会运行,它会做几件事,包括启动一个 java 应用程序。我收到的问题是当 c# 应用程序终止时,bash 脚本/java 应用程序也会终止。

我查看了 Stack Overflow 上发布的其他几个类似问题,但没有一个得出明显的结论,包括这个:

How to create a Process that outlives its parent

根据一些用户和据称的文档,由 Process.Start() 创建的进程不应在应用程序终止时终止,但显然在我的情况下这是不正确的。那么这可能是一个与 Mono 相关的问题吗?如果确实如此,那么我现在的做法是否有任何替代方案,因为我没有想法。

【问题讨论】:

  • 这绝对不会在 Windows 中发生,所以是的,这一定是 mono/nix 特定的。
  • 请将您的更新发布为新答案,然后将其标记为解决方案。

标签: c# linux process mono


【解决方案1】:

这是一个适合我的完整示例:

using System;
using System.Diagnostics;

class Tick {
  static void Main(string[] args) {  
    Process p = new Process();

    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = false;
    p.StartInfo.RedirectStandardInput = true;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
    p.StartInfo.FileName = "/bin/sh";
    p.StartInfo.Arguments = "test.sh";

    p.EnableRaisingEvents = true;
    p.ErrorDataReceived += new DataReceivedEventHandle(ShellProc_ErrorDataReceived);

    p.Start();
    System.Threading.Thread.Sleep (5000);
    Console.WriteLine ("done");
  }  
  static void ShellProc_ErrorDataReceived (object sender, DataReceivedEventArgs ea)
  {
  }
}

然后 test.sh 是:

while true; do
    date;
    sleep 1;
done

当我从终端运行示例时,test.sh 脚本将在示例程序退出后继续输出数据。

【讨论】:

  • 谢谢,在测试后我意识到问题完全是我的错,是在应用程序的另一个区域调用了一些 GC 东西,导致应用程序创建的进程关闭.你帮助我意识到我哪里出错了,谢谢!
【解决方案2】:

更新 1/解决方案:这实际上不是 mono 的错,而且确实是我自己的错,下面的答案帮助我得出结论,是我的应用程序中的其他东西导致了这些进程由应用程序启动以在应用程序终止时终止,而导致这种情况的实际原因是一些 GC 的东西,特别是 GC.Collect(),我的错,对不起,我希望这对遇到类似问题的人有所帮助。

【讨论】:

    猜你喜欢
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    相关资源
    最近更新 更多