2015-04-28 2 views
1

мне нужна помощь с классом QProcess метод называется „выполнить“Qt QProccess с пингом использованием утилиты

Я хочу знать, сервер живо, используя внешнюю программу „звон“ в windows7. я делаю:

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!"; 
} 

Внешние отпечатки в консоль некоторую информацию, что я не хочу видеть. В идеале я хочу запустить мою функцию (часть ее тела написана сверху) в дочернем потоке. Другими словами, я просто хочу получить «Это мертво \ живое!» в консоли из этих кодовых строк

+0

Для какой ОС вам это нужно? – vahancho

+0

Я пишу свое маленькое приложение для NT, особенно в \ for windows7 x32 ultimate – user3780183

ответ

1

Для этого потребуется немного больше работы. Вам нужно рассматривать QProcess как IODevice, прислушиваясь к его сигналу readyRead(), когда вся информация доступна из него.

Вот полный код, чтобы сделать то, что вы хотите:

Pinger.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 

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(); 
    } 
} 
+0

Да! Это то, что я искал. Большое вам спасибо, он отлично работает. – user3780183

Смежные вопросы