在Qt控制台程序中,当程序关闭时,可以通过捕捉一些特定的信号来执行清理操作或保存状态。常见的信号包括:
- 用户发送的终止信号(如Ctrl+C产生的SIGINT信号)。(Windows 支持,已验证)
- 终止请求(如kill命令产生的SIGTERM信号)。
- 其他信号如SIGHUP(挂起)。
示例代码:
#include <QCoreApplication>
#include <QObject>
#include <csignal>
#include <iostream>
void signalHandler(int signal) {
std::cerr << "Caught signal " << signal << ". Cleaning up and exiting."
<< std::endl;
// 执行清理操作
// ...
// 退出程序
QCoreApplication::quit();
}
void cleanup() {
std::cout << "Performing cleanup before quitting." << std::endl;
// 执行清理操作
// ...
}
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
// 设置信号处理函数
#if defined(Q_OS_WINDOWS)
std::signal(SIGINT, signalHandler); // 捕捉Ctrl+C
std::signal(SIGTERM, signalHandler); // 捕捉terminate信号
#elif defined(Q_OS_MACOS)
#elif defined(Q_OS_LINUX)
#elif defined(Q_OS_ANDROID)
#elif defined(Q_OS_IOS)
#endif
QObject::connect(&app, &QCoreApplication::aboutToQuit, &cleanup);
std::cout << "Press Ctrl+C to exit the program." << std::endl;
return app.exec();
}