Detect when console application is closing/killed?(检测控制台应用程序何时关闭/终止?)
问题描述
我想为我的控制台应用程序安全退出,该应用程序将使用单声道在 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.
如何在我的控制台应用程序上获得关闭事件以安全退出它?
How do I get a closing event on my console application to safe exit it ?
推荐答案
你需要使用 Mono.UnixSignal
,Jonathan Pryor 发布了一个很好的示例:http://www.jprl.com/Blog/archive/development/mono/2008/Feb-08.html一个>
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 页面上还有一个较短的示例:FAQ/技术/操作系统问题/信号处理:
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); });
}});
这篇关于检测控制台应用程序何时关闭/终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检测控制台应用程序何时关闭/终止?
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 使用 rss + c# 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01