优雅地杀死在 Linux 上运行的 .NET Core 守护进程 [英] Killing gracefully a .NET Core daemon running on Linux

查看:59
本文介绍了优雅地杀死在 Linux 上运行的 .NET Core 守护进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 .NET Core 控制台应用程序,在 Ubuntu 14.04 机器上作为守护程序运行.

I created a .NET Core console application running as a daemon on a Ubuntu 14.04 machine.

我想在不强制的情况下停止服务,以便能够处理终止事件.

I want to stop the service without forcing it, being able to handle a kill event.

我怎样才能做到这一点?

How can I achieve this?

推荐答案

您希望能够向正在运行的进程发送一个SIGTERM:

You want to be able to send a SIGTERM to the running process:

kill <PID>

并且进程应该处理它以正确关闭.

And the process should handle it to shutdown correctly.

不幸的是,.NET Core 没有很好的文档记录,但它能够处理 Unix 信号(以不同于 Mono 的方式).GitHub 问题

Unfortunately .NET Core is not well documented, but it is capable of handling Unix signals (in a different fashion from Mono). GitHub issue

如果您将 UbuntuUpstart 一起使用,您需要的是一个 init 脚本,用于在停止请求时发送 kill 信号: 示例初始化脚本

If you use Ubuntu with Upstart, what you need is to have an init script that sends the the kill signal on a stop request: Example init script

向您的 project.json 添加依赖项:

Add a dependency to your project.json:

"System.Runtime.Loader": "4.0.0"

这将为您提供 AssemblyLoadContext.

然后就可以处理SIGTERM事件了:

Then you can handle the SIGTERM event:

AssemblyLoadContext.Default.Unloading += MethodInvokedOnSigTerm;

注意:

使用 Mono,正确的处理方式是通过 UnixSignal:Mono.Unix.Native.Signum.SIGTERM

Using Mono, the correct way of handling it would be through the UnixSignal: Mono.Unix.Native.Signum.SIGTERM

正如@Marc 在他最近的回答中指出的那样,这不再是实现这一目标的最佳方式.从 .NET Core 2.0 开始,AppDomain.CurrentDomain.ProcessExit 是支持的事件.

As @Marc pointed out in his recent answer, this is not anymore the best way to achieve this. From .NET Core 2.0 AppDomain.CurrentDomain.ProcessExit is the supported event.

这篇关于优雅地杀死在 Linux 上运行的 .NET Core 守护进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆