::write() 和 ::read() 尚未声明错误。Qt5 UNIX 信号处理

Ra4*_*41P 1 c++ unix linux signals qt5

所以,我尝试按照给出的教程进行操作

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);
}
Run Code Online (Sandbox Code Playgroud)

现在,当我创建 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], &a, sizeof(a)); ^

对于 ::read() 或 ::write() 调用的所有实例,依此类推。我不确定我做错了什么,我很感激任何帮助:)

Mat*_*son 5

如果您使用“基本”Unix 功能,则需要使用

#include <unistd.h>
Run Code Online (Sandbox Code Playgroud)

这将为您提供readwriteopenclosesleepusleep许多其他功能。