I'm curious if a console app written in .NET Core running on Windows can intercept a SIGKILL event and basically know it's being terminated. Here's the code I'm trying:
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine($"Hello from PID {Process.GetCurrentProcess().Id}, press CTRL+C to exit.");
AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()).Unloading += context =>
{
Console.WriteLine("SIGTERM received, exiting program...");
};
Console.CancelKeyPress += (s, e) =>
{
Console.WriteLine("SIGINT received, exiting program...");
Environment.Exit(0);
};
try
{
await Task.Delay(Timeout.Infinite);
}
finally
{
Console.WriteLine("Finally executed..");
}
}
When I run the program from the command line, I can terminate it with the CTRL+C key combination. This will fire CancelKeyPress as well as Unloading. If I terminate the program other ways (Using the Windows Task Manager "End Process" function, or the Stop-Process PowerShell command), the process simply ends without any output written to the console.
This is part of a larger goal, which is to trap a Docker container shutting down. On Windows, the docker stop command will kill the main process using SIGTERM. This behavior is configurable on Linux Docker using the --stop-signal or STOPSIGNAL features, but those things have not been implemented on Windows.
