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); });
}});
这篇关于检测控制台应用程序何时关闭/终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检测控制台应用程序何时关闭/终止?
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01