Hello
The issue arises because QTextStream(stdin).readLine() is a blocking call, and signals like SIGTERM are not handled immediately during such operations. The signal handler will execute only after the blocking call completes.
Solution:
Use non-blocking I/O with QSocketNotifier to read from stdin asynchronously, allowing signals to be handled promptly:
#include <QCoreApplication>
#include <QSocketNotifier>
#include <QTextStream>
#include <signal.h>
void signalHandler(int) {
if (app) app->quit();
}
int main(int argc, char* argv[]) {
app = &application;
signal(SIGTERM, signalHandler); // Register signal handler
QObject::connect(¬ifier,
&QSocketNotifier
::activated,
[&]() { if (!line.isEmpty()) qDebug() << "Input:" << line;
});
return application.exec();
}
#include <QCoreApplication>
#include <QSocketNotifier>
#include <QTextStream>
#include <signal.h>
QCoreApplication* app = nullptr;
void signalHandler(int) {
if (app) app->quit();
}
int main(int argc, char* argv[]) {
QCoreApplication application(argc, argv);
app = &application;
signal(SIGTERM, signalHandler); // Register signal handler
QSocketNotifier notifier(STDIN_FILENO, QSocketNotifier::Read);
QObject::connect(¬ifier, &QSocketNotifier::activated, [&]() {
QTextStream input(stdin);
QString line = input.readLine();
if (!line.isEmpty()) qDebug() << "Input:" << line;
});
return application.exec();
}
To copy to clipboard, switch view to plain text mode
This ensures signal handling works even while waiting for input.
Bookmarks