控制台程序终止时调用特定函数(Call a specific function when the console program terminates)

编程入门 行业动态 更新时间:2024-10-28 02:23:49
控制台程序终止时调用特定函数(Call a specific function when the console program terminates)

我在Windows上,我希望在程序终止时调用特定的函数。

例如:

void close_program() { /*do stuff*/ printf("Goodbye.\n"); }

我尝试了atexit()但它只适用于临时和常规出口,例如调用函数exit()或者当main向操作系统返回值时。

我发现HandlerRoutine()似乎是一个解决方案,因为Windows将CTRL_CLOSE_EVENT值信号发送给用户关闭的进程(通过任务管理器关闭按钮或结束任务)。 问题是我尝试了一段非常基本的代码,它说'未定义对HandlerRoutine的引用'并返回1。

这段代码:

#include <stdio.h> #include <windows.h> int main() { while(1) { if(HandlerRoutine(CTRL_CLOSE_EVENT)) { printf("Program is being terminated...\n"); } } return 0; }

我用MinGW。

知道问题可能是什么?

根据MSDN ,不需要链接。

I'm on windows and I want to call a specific function when the program terminates.

For example:

void close_program() { /*do stuff*/ printf("Goodbye.\n"); }

I tried atexit() but it only worked on casual and regular exits such as a call to the function exit() or when the main returns a value to the OS.

I found out that HandlerRoutine() seems like a solution as windows sends a CTRL_CLOSE_EVENT value signal to the process closed by the user (either just close button or end task through task manager). The problem is I tried a really basic piece of code and it said 'undefined reference to HandlerRoutine' and that it returned 1.

The piece of code:

#include <stdio.h> #include <windows.h> int main() { while(1) { if(HandlerRoutine(CTRL_CLOSE_EVENT)) { printf("Program is being terminated...\n"); } } return 0; }

I use MinGW.

Any idea what is the problem might be ?

According to MSDN there is no need for linkage.

最满意答案

从您链接的MSDN页面

HandlerRoutine是应用程序定义的函数名称的占位符。

您需要做的是创建一个回调(PHANDLER_ROUTINE类型),然后使用SetConsoleCtrlHandler注册此回调。

From the MSDN page you linked

HandlerRoutine is a placeholder for the application-defined function name.

What you need to do is create a callback (of PHANDLER_ROUTINE type) and then use SetConsoleCtrlHandler to register this callback.

更多推荐

本文发布于:2023-08-07 08:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1463307.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时调   控制台   函数   程序   Call

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!