gpt4 book ai didi

c++ - 使用 ping 实用程序的 Qt QProccess

转载 作者:行者123 更新时间:2023-11-30 05:44:09 25 4
gpt4 key购买 nike

我需要一些关于 QProcess 类的方法“execute”的帮助

我想知道在 Windows7 中使用外部实用程序“ping”的服务器是否处于事件状态。我做:

int exitCode = QProcess::execute(QString("ping -n %1 %2").arg(packetNumber).arg(hostAddr.toString()));
if (exitCode == 0){
// it's alive
qDebug() << "It's alive!";
}
else{
// it's dead
qDebug() << "It's dead!";
}

外部打印到控制台的一些信息,我不想看到。理想情况下,我想在子线程中运行我的函数(它的一部分写在上面)。换句话说,我只想得到“它死了\活了!”在这些代码行的控制台中

最佳答案

这需要更多的工作。您需要将 QProcess 视为一个 IODevice,监听它的 readyRead() 信号以获取任何可用的信息。

这里是完成你想做的事情的完整代码:

平儿.h

#ifndef PINGER_H
#define PINGER_H

#include <QtCore/QTimer>
#include <QtCore/QProcess>

/// \brief Starts pinging a specified url constantly
/// As soon as ping fails, it emits a 'pingFailed'
/// signal
class Pinger : public QObject
{
Q_OBJECT
public:
Pinger();
~Pinger();

/// \brief Starts a ping check in a loop
/// \param[in] urlToPing The url that needs to be pinged continuously
/// \param[in] pingInterval Interval (in seconds) at which specified url must be pinged
void startPingCheck(const QString& urlToPing, const int& pingIntervalInSecs = 5);

signals:
/// \brief Signal emitted when pinging of specified url fails
void pingFailed();

private slots:
/// \brief Slot called periodically to ping specified url
void _pingExec();

/// \brief Slot called when ping process returns a message
void _handleProcessMessage();

private:
/// \brief Timer used to ping repeatedly
QTimer _pingTimer;

/// \brief Ping process
QProcess _pingProcess;

/// \brief Pinged url
QString _pingUrl;
};

#endif // PINGER_H

平儿.cpp

#include <QtCore/QDebug>

#include "pinger.h"

Pinger::Pinger():
_pingUrl("8.8.8.8")
{

}

Pinger::~Pinger()
{

}

void Pinger::startPingCheck(const QString& urlToPing, const int& pingInterval)
{
_pingUrl = urlToPing;

// Listen for messages from the ping process
connect(&_pingProcess, SIGNAL(readyRead()), this, SLOT(_handleProcessMessage()));

// Connect the timer to the exec method that actually calls the ping process
_pingTimer.setInterval(pingInterval * 1000);
_pingTimer.setSingleShot(false);
connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(_pingExec()));
_pingTimer.start();
}

void Pinger::_pingExec()
{
QStringList arguments;
arguments << "-n" << "1" << _pingUrl;
_pingProcess.start("ping", arguments);
}

void Pinger::_handleProcessMessage()
{
QByteArray response = _pingProcess.readAll();
QString responseStr(response);
if(responseStr.contains("100% loss"))
{
qDebug() << "Ping failed. " << _pingUrl << " down.";
emit pingFailed();
}
}

关于c++ - 使用 ping 实用程序的 Qt QProccess,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29920800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com