Detect when console application is closing/killed?

后端 未结 2 970
一个人的身影
一个人的身影 2020-12-11 14:28

I wanted to make a safe exit for my console application that will be running on linux using mono but I can\'t find a solution to detect wether a signal was sent to it or the

2条回答
  •  囚心锁ツ
    2020-12-11 15:27

    You need to use Mono.UnixSignal, there's a good sample posted by Jonathan Pryor : http://www.jprl.com/Blog/archive/development/mono/2008/Feb-08.html

    There's also a shorter example on Mono page: FAQ / Technical / Operating System Questions / Signal Handling:

    // Catch SIGINT and SIGUSR1
    UnixSignal[] signals = new UnixSignal [] {
        new UnixSignal (Mono.Unix.Native.Signum.SIGINT),
        new UnixSignal (Mono.Unix.Native.Signum.SIGUSR1),
    };
    
    Thread signal_thread = new Thread (delegate () {
        while (true) {
            // Wait for a signal to be delivered
            int index = UnixSignal.WaitAny (signals, -1);
    
            Mono.Unix.Native.Signum signal = signals [index].Signum;
    
            // Notify the main thread that a signal was received,
            // you can use things like:
            //    Application.Invoke () for Gtk#
            //    Control.Invoke on Windows.Forms
            //    Write to a pipe created with UnixPipes for server apps.
            //    Use an AutoResetEvent
    
            // For example, this works with Gtk#    
            Application.Invoke (delegate () { ReceivedSignal (signal); });
        }});
    

提交回复
热议问题