1 /* Basic code to enable LADISH level 1 support to an event driven Qt (3/4)
3 * (c) 2010 Guido Scholz, License: GNU GPL v2
8 /* Add this declaration to the header file of your MainWindow class:*/
11 static int sigpipe
[2];
13 static void handleSignal(int);
14 bool installSignalHandlers();
17 void signalAction(int);
22 /* Add this code to the cpp file of your MainWindow class:*/
24 #include <cerrno> // for errno
25 #include <csignal> // for sigaction()
26 #include <cstring> // for strerror()
27 #include <unistd.h> // for pipe()
28 #include <QSocketNotifier>
31 int MainWindow::sigpipe
[2];
34 MainWindow::MainWindow(...)
37 /*add this lines to the constuctor of your MainWindow class: */
38 if (!installSignalHandlers())
39 qWarning("%s", "Signal handlers not installed!");
45 /* Handler for system signals (SIGUSR1, SIGINT...)
46 * Write a message to the pipe and leave as soon as possible
48 void MainWindow::handleSignal(int sig
)
50 if (write(sigpipe
[1], &sig
, sizeof(sig
)) == -1) {
51 qWarning("write() failed: %s", std::strerror(errno
));
55 /* Install signal handlers (may be more than one; called from the
56 * constructor of your MainWindow class*/
57 bool MainWindow::installSignalHandlers()
59 /*install pipe to forward received system signals*/
60 if (pipe(sigpipe
) < 0) {
61 qWarning("pipe() failed: %s", std::strerror(errno
));
65 /*install notifier to handle pipe messages*/
66 QSocketNotifier
* signalNotifier
= new QSocketNotifier(sigpipe
[0],
67 QSocketNotifier::Read
, this);
68 connect(signalNotifier
, SIGNAL(activated(int)),
69 this, SLOT(signalAction(int)));
71 /*install signal handlers*/
72 struct sigaction action
;
73 memset(&action
, 0, sizeof(action
));
74 action
.sa_handler
= handleSignal
;
76 if (sigaction(SIGUSR1
, &action
, NULL
) == -1) {
77 qWarning("sigaction() failed: %s", std::strerror(errno
));
81 /* optional: register more signals to handle:
82 if (sigaction(SIGINT, &action, NULL) == -1) {
83 qWarning("sigaction() failed: %s", std::strerror(errno));
91 /* Slot to give response to the incoming pipe message;
92 e.g.: save current file */
93 void MainWindow::signalAction(int fd
)
97 if (read(fd
, &message
, sizeof(message
)) == -1) {
98 qWarning("read() failed: %s", std::strerror(errno
));
106 /* optional: handle more signals:
108 //do something usefull like ...
113 qWarning("Unexpected signal received: %d", message
);