我想为我的控制台应用程序安全退出,该应用程序将使用单声道在 linux 上运行,但我找不到解决方案来检测信号是否发送到它或用户是否按下了 ctrl+c。
在 Windows 上有内核函数 SetConsoleCtrlHandler 可以完成这项工作,但它不适用于单声道。
如何在我的控制台应用程序上获得关闭事件以安全退出它?
最佳答案
您需要使用 Mono.UnixSignal
,Jonathan Pryor 发布了一个很好的示例:http://www.jprl.com/Blog/archive/development/mono/2008/Feb-08.html
Mono 页面上还有一个较短的示例: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); });
}});
关于c# - 检测控制台应用程序何时关闭/终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6546509/