我无法从我的 .net 核心控制台应用程序处理 kubernets 的应用程序生命周期事件

问题描述 投票:0回答:1

我正在尝试在我的应用程序上处理 kuberenetes 的预停止事件,但我没有在我的 .net 核心控制台应用程序上收到任何事件

lifecycle:
      postStart:
        tcpSocket:
          port: 13000
      preStop:
        tcpSocket:
          port: 13001

我在事件日志中收到

FailedPreStopHook pod/podname-795764db56-9q9pg 无法运行 处理程序:无效处理程序: &LifecycleHandler{Exec:nil,HTTPGet:nil,TCPSocket:&TCPSocketAction{端口:{0 13001 },主机:,},}

我尝试了另一种解决方案来开始使用原生函数,例如

[DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(SetConsoleCtrlEventHandler handler, bool add);

但是我只能在 windows 环境下运行它但是一旦我进入 linux 容器我收到错误

未处理的异常。 System.DllNotFoundException:无法加载 共享库“Kernel32”或其依赖项之一。为了帮助 诊断加载问题,考虑设置 LD_DEBUG 环境 变量:libKernel32:无法打开共享对象文件:没有这样的文件或 目录

请告知是否有任何其他解决方案可以解决此问题,以便在 linux contianer 环境上顺利处理 consol 应用程序的关闭。

c# docker kubernetes .net-core console-application
1个回答
0
投票

AppDomain.CurrentDomain.ProcessExit
SIGTERM
上提出
Console.CancelKeyPress
SIGINT 上提出。

static void Main(string[] args)
{
    Console.WriteLine();
    Console.WriteLine($"Process ID = {Environment.ProcessId}");
    var cancel = false;
    Console.CancelKeyPress += new ConsoleCancelEventHandler((s, e) =>
    {
        Console.WriteLine($"CancelKeyPress");
        cancel = true;
    });
    AppDomain.CurrentDomain.ProcessExit += new EventHandler((s, e) =>
    {
        Console.WriteLine($"ProcessExit");
        cancel = true;
    });
    do
    {
        Thread.Sleep(10);
    } while (!cancel);
    Console.WriteLine($"Process {Environment.ProcessId} exited gracefully.");
}

结果:

$ dotnet run &
Process ID = 4113
$ kill -s INT 4113
CancelKeyPress
Process 4113 exited gracefully.
$ dotnet run &
Process ID = 4395
$ kill -s TERM 4395
ProcessExit
Process 4395 exited gracefully.
© www.soinside.com 2019 - 2024. All rights reserved.