source: trunk/doc/src/snippets/code/doc_src_unix-signal-handlers.qdoc@ 5

Last change on this file since 5 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 2.1 KB
Line 
1//! [0]
2class MyDaemon : public QObject
3{
4 Q_OBJECT
5
6 public:
7 MyDaemon(QObject *parent = 0, const char *name = 0);
8 ~MyDaemon();
9
10 // Unix signal handlers.
11 static void hupSignalHandler(int unused);
12 static void termSignalHandler(int unused);
13
14 public slots:
15 // Qt signal handlers.
16 void handleSigHup();
17 void handleSigTerm();
18
19 private:
20 static int sighupFd[2];
21 static int sigtermFd[2];
22
23 QSocketNotifier *snHup;
24 QSocketNotifier *snTerm;
25};
26//! [0]
27
28
29//! [1]
30MyDaemon::MyDaemon(QObject *parent, const char *name)
31 : QObject(parent,name)
32{
33 if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sighupFd))
34 qFatal("Couldn't create HUP socketpair");
35
36 if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigtermFd))
37 qFatal("Couldn't create TERM socketpair");
38 snHup = new QSocketNotifier(sighupFd[1], QSocketNotifier::Read, this);
39 connect(snHup, SIGNAL(activated(int)), this, SLOT(handleSigHup()));
40 snTerm = new QSocketNotifier(sigtermFd[1], QSocketNotifier::Read, this);
41 connect(snTerm, SIGNAL(activated(int)), this, SLOT(handleSigTerm()));
42
43 ...
44}
45//! [1]
46
47
48//! [2]
49static int setup_unix_signal_handlers()
50{
51 struct sigaction hup, term;
52
53 hup.sa_handler = MyDaemon::hupSignalHandler;
54 sigemptyset(&hup.sa_mask);
55 hup.sa_flags = 0;
56 hup.sa_flags |= SA_RESTART;
57
58 if (sigaction(SIGHUP, &hup, 0) > 0)
59 return 1;
60
61 term.sa_handler = MyDaemon::termSignalHandler;
62 sigemptyset(&term.sa_mask);
63 term.sa_flags |= SA_RESTART;
64
65 if (sigaction(SIGTERM, &term, 0) > 0)
66 return 2;
67
68 return 0;
69}
70//! [2]
71
72
73//! [3]
74void MyDaemon::hupSignalHandler(int)
75{
76 char a = 1;
77 ::write(sighupFd[0], &a, sizeof(a));
78}
79
80void MyDaemon::termSignalHandler(int)
81{
82 char a = 1;
83 ::write(sigtermFd[0], &a, sizeof(a));
84}
85//! [3]
86
87
88//! [4]
89void MyDaemon::handleSigTerm()
90{
91 snTerm->setEnabled(false);
92 char tmp;
93 ::read(sigtermFd[1], &tmp, sizeof(tmp));
94
95 // do Qt stuff
96
97 snTerm->setEnabled(true);
98}
99
100void MyDaemon::handleSigHup()
101{
102 snHup->setEnabled(false);
103 char tmp;
104 ::read(sighupFd[1], &tmp, sizeof(tmp));
105
106 // do Qt stuff
107
108 snHup->setEnabled(true);
109}
110//! [4]
Note: See TracBrowser for help on using the repository browser.