问题描述
我想作一个安全出口的,这将在Linux上使用单声道运行我的控制台应用程序,但我不能找到一个解决方案来检测阉信号发送给它或用户按下Ctrl + C。
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 user pressed ctrl+c.
在Windows,有一个核函数SetConsoleCtrlHandler该做这项工作,但是,单是行不通的。
On windows there is the kernel function SetConsoleCtrlHandler which does the job but that doesnt work on mono.
我如何获得在我的控制台应用程序安全出口它closing事件?
How do I get a closing event on my console application to safe exit it ?
推荐答案
您需要使用 Mono.UnixSignal
,还有张贴乔纳森·普赖尔一个很好的例子:
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
还有在Mono较短的例子页面::
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); });
}});
这篇关于检测时,控制台应用程序正在关闭/杀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!