我需要有关QProcess类的称为“执行”的方法的帮助

我想知道在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()信号。

这是执行所需操作的完整代码:

宾格

#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

Pinger.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++ - Qt QProccess与ping实用程序用法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29920800/

10-09 06:36