【问题标题】:Killing a C# process gracefully not working优雅地终止 C# 进程不起作用
【发布时间】:2016-05-31 01:57:59
【问题描述】:

我有一个产生多个线程的应用程序,其中一个线程运行一个iPerf 可执行文件,用于监控网络可靠性。此过程将无限期运行,直到用户尝试关闭窗口。这就是问题所在。我正在尝试优雅地关闭该进程,以便iPerf 服务器不会挂起,但我似乎无法使其正常工作。如果我从命令提示符手动运行命令并按Ctrl+c,我可以很好地关闭它,但这似乎并不容易以编程方式完成。

我尝试了多种方法,包括process.Kill();process.StandardInput.Close() 甚至process.StandardInput.WriteLine("\x3");,但这些方法似乎都没有向进程发送正常关闭消息。 process.Kill(); 导致服务器挂起或下次启动失败,其他两个选项根本不停止服务器。但是手册ctrl+c 工作得很好。

这是我的代码的 sn-p:

iperf_proc = new Process();
iperf_proc.StartInfo.FileName = Application.StartupPath + ".\\iperf3.exe";
String argumentStr = " -c " + test_data.host + " -t 0";
iperf_proc.StartInfo.Arguments = argumentStr;
iperf_proc.StartInfo.UseShellExecute = false;
iperf_proc.StartInfo.RedirectStandardOutput = true;
iperf_proc.StartInfo.RedirectStandardInput = true;
iperf_proc.StartInfo.RedirectStandardError = true;
iperf_proc.Start();
iperfRunning = true;
iperf_proc.BeginOutputReadLine();
iperf_proc.BeginErrorReadLine();
while (false == iperf_proc.HasExited)
{
    if (true == processCancelled)
    {
        iperf_proc.StandardInput.Close(); // Doesn't Work!
        iperf_proc.StandardInput.WriteLine("\x3"); // Doesn't Work!
        iperf_proc.StandardInput.Flush(); // Doesn't Work!
    }
}
iperf_proc.WaitForExit();

非常感谢任何帮助。谢谢!

更新:

根据 Hans 在评论中的建议,我尝试在代码中添加一些内容以发送 ctrl+c 事件。

[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GenerateConsoleCtrlEvent(uint dwCtrlEvent, uint dwProcessGroupId);
private enum CtrlEvents
{
     CTRL_C_EVENT = 0,
     CTRL_BREAK_EVENT = 1
}
private void closeBtn_Click(object sender, EventArgs e)
{
     processCancelled = true;
     //iperf_proc.CloseMainWindow();
     bool succeeded = GenerateConsoleCtrlEvent((uint)CtrlEvents.CTRL_C_EVENT, (uint)iperf_proc.Id);
}

这根本不起作用。该过程仍在运行,并且添加的功能返回false。我确实检查了传递的进程 ID 是否与任务管理器中的进程 ID 匹配。这一切都很好,但是 GenerateConsoleCtrlEvent 函数返回 false。知道为什么会这样吗?

【问题讨论】:

  • @HansPassant 感谢您的链接。也许我没有正确理解链接或错误地实现了代码,但我已经在上面相应地更新了我的问题以显示我为此控制台事件添加的代码,它似乎并没有真正做任何事情。
  • 还请注意,我需要能够尽可能接近实时地访问此过程的输出。

标签: c# .net process iperf


【解决方案1】:

BeginOutputReadLine

链接描述了如何在示例中完全按照您的要求进行操作。

为什么不使用内置的 Exited 事件来等待,这样您就不会阻塞?特别是如果您正在生成多个线程。如果你想阻止,那么 WaitForExit() 也是可用的。

if (true == processCancelled)
{
    iperf_proc.StandardInput.Close(); // Doesn't Work!
    iperf_proc.StandardInput.WriteLine("\x3"); // Doesn't Work!
    iperf_proc.StandardInput.Flush(); // Doesn't Work!
}

如果你关闭标准输入,你打算怎么写/刷新它?

拥有 WaitForExit() 后,还需要 Close()

【讨论】:

  • 我应该更清楚一点,这里的行不一定是按这个顺序排列的,甚至不是一次全部在代码中。只是展示我尝试过的东西。
  • 我也不完全确定您是否理解我的要求。我需要优雅地关闭一个我有句柄的进程。如果这个进程没有正常关闭,它会使服务器挂起。
猜你喜欢
  • 2011-01-04
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多