所以,我正在尝试按照给出的教程
http://qt-project.org/doc/qt-5/unix-signals.html
捕获UNIX / Linux信号并在它们触发时执行与Qt相关的操作。
这是关于qtDocs的,所以我认为它是合法的。
我现在的代码如下:
mydaemon.cpp
#include "mydaemon.h"
#include <QDebug>
#include <QObject>
#include <QSocketNotifier>
#include <csignal>
#include <sys/socket.h>
#include <iostream>
#include <stdio.h>
#include <signal.h>
//needed to not get an undefined reference to static members
int MyDaemon::sighupFd[2];
int MyDaemon::sigtermFd[2];
MyDaemon::MyDaemon(QObject *parent)
: QObject(parent)
{
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sighupFd))
qFatal("Couldn't create HUP socketpair");
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigtermFd))
qFatal("Couldn't create TERM socketpair");
snHup = new QSocketNotifier(sighupFd[1], QSocketNotifier::Read, this);
connect(snHup, SIGNAL(activated(int)), this, SLOT(handleSigHup()));
snTerm = new QSocketNotifier(sigtermFd[1], QSocketNotifier::Read, this);
connect(snTerm, SIGNAL(activated(int)), this, SLOT(handleSigTerm()));
}
MyDaemon::~MyDaemon() {}
void MyDaemon::hupSignalHandler(int)
{
qDebug() << "signal hup";
char a = '1';
::write(sighupFd[0], &a, sizeof(a));
}
void MyDaemon::termSignalHandler(int)
{
qDebug() << "signal term";
char a = '1';
::write(sigtermFd[0], &a, sizeof(a));
}
void MyDaemon::handleSigTerm()
{
snTerm->setEnabled(false);
char tmp;
::read(sigtermFd[1], &tmp, sizeof(tmp));
// do Qt stuff
qDebug() << "MyDaemon::handleSigTerm";
snTerm->setEnabled(true);
}
void MyDaemon::handleSigHup()
{
snHup->setEnabled(false);
char tmp;
::read(sighupFd[1], &tmp, sizeof(tmp));
// do Qt stuff
qDebug() << "MyDaemon::handleSigHup";
snHup->setEnabled(true);
}
现在,当我创建我的C ++类并尝试构建时,它会给出错误,例如
/ home / xxxx / Documents / Qt Projects / mainScreen / mydaemon.cpp:-1:在静态成员函数中'static void MyDaemon :: termSignalHandler(int)': / home / xxxx / Documents / Qt Projects / mainScreen / mydaemon.cpp:49:错误:':: write'尚未声明 :: write(sigtermFd [0],&amp; a,sizeof(a)); ^
等等,对于:: read()或:: write()调用的所有实例。我不确定我做错了什么,我很感激任何帮助:)
答案 0 :(得分:2)
如果您使用的是“基本”Unix功能,则需要使用
#include <unistd.h>
这会为您提供read
,write
,open
,close
,sleep
,usleep
以及许多其他功能。