user4388177 user4388177 - 3 months ago 36
Linux Question

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?

Answer Source

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;


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download