Qt QProccess使用ping实用程序

时间:2015-04-28 13:22:15

标签: c++ qt c++11

我需要一些名为“execute”的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!";
}

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

1 个答案:

答案 0 :(得分:1)

这需要更多的工作。您需要将QProcess视为IODevice,只要有信息,就可以收听readyRead()信号。

以下是完成您想要的完整代码:

Pinger.h

 <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />

Pinger.cpp

#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