Reputation: 6323
I want to dump data to a file on program termination, whether it be "Ctrl-C" or some other means in Linux.
Not sure how to capture the program closing or terminating event/s?
Upvotes: 1
Views: 608
Reputation: 187
QCoreApplication (and thus QApplication) has a signal aboutToQuit() that will be emitted when the application is about to quit the main event loop. Connect it to a slot that dumps your data and you should be fine.
Upvotes: 1
Reputation: 55620
You need to handle Linux-style signals. Note - this will not work on Windows or Mac if you are trying to be cross platform.
See the Qt article Calling Qt Functions From Unix Signal Handlers.
Here is a minimal setup example extracted from the article:
class MyDaemon : public QObject
{
...
public:
static void hupSignalHandler(int unused);
public slots:
void handleSigHup();
private:
static int sighupFd[2];
QSocketNotifier *snHup;
};
MyDaemon::MyDaemon(...)
{
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sighupFd))
qFatal("Couldn't create HUP socketpair");
snHup = new QSocketNotifier(sighupFd[1], QSocketNotifier::Read, this);
connect(snHup, SIGNAL(activated(int)), this, SLOT(handleSigHup()));
}
static int setup_unix_signal_handlers()
{
struct sigaction hup;
hup.sa_handler = MyDaemon::hupSignalHandler;
sigemptyset(&hup.sa_mask);
hup.sa_flags = 0;
hup.sa_flags |= SA_RESTART;
if (sigaction(SIGHUP, &hup, 0) > 0)
return 1;
return 0;
}
void MyDaemon::hupSignalHandler(int)
{
char a = 1;
::write(sighupFd[0], &a, sizeof(a));
}
void MyDaemon::handleSigHup()
{
snHup->setEnabled(false);
char tmp;
::read(sighupFd[1], &tmp, sizeof(tmp));
// do Qt stuff
snHup->setEnabled(true);
}
Upvotes: 1