Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

c# - Killing gracefully a .NET Core daemon running on Linux

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?

question from:https://stackoverflow.com/questions/38291567/killing-gracefully-a-net-core-daemon-running-on-linux

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

kill <PID>

And the process should handle it to shutdown correctly.

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

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

Add a dependency to your project.json:

"System.Runtime.Loader": "4.0.0"

This will give you the AssemblyLoadContext.

Then you can handle the SIGTERM event:

AssemblyLoadContext.Default.Unloading += MethodInvokedOnSigTerm;

Note:

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

EDIT:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...