Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 745
user4388177 Avatar asked Jul 10 '16 11:07

user4388177


People also ask

Does .NET Core run on Linux?

NET Core runtime allows you to run applications on Linux that were made with .

Is .NET Core faster on Linux?

Results are consistent with those obtained generating load from a computer connected through wire to the internet: the same ASP.NET Core application deployed in Linux and Docker is much faster than one deployed in Windows host (both inside Application Service Plan).


2 Answers

.NET Core has considerably evolved since @Stefano's answer a year ago. In .NET Core 2.0, you can now use the well-known AppDomain.CurrentDomain.ProcessExit event instead of AssemblyLoadContext.Default.Unloading. It works fine for console applications on Linux, also in Docker.

like image 155
Marc Sigrist Avatar answered Sep 28 '22 16:09

Marc Sigrist


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.

like image 27
Stefano d'Antonio Avatar answered Sep 28 '22 14:09

Stefano d'Antonio