首页 文章

启动并写入Qt的终端

提问于
浏览
1

我使用Qt在linux中编码 . 我知道使用popen或QProcess我可以从我的程序启动终端,但我该如何写入呢?我谷歌周围的人建议fork()和管道() . 我的目的是与终端进行ICMP ping,并在ping成功时停止 . 我用popen制作了,但是我无法停止ping过程,因此我的程序将无法运行 .

1 回答

  • 1

    你没有't write anything to terminal because there'没有终端 . 您将要运行的程序的名称及其参数作为QProcess::start方法的参数传递 . 如果您只需要知道ping是否成功,那么使用 QProcess::start 检查您之前开始的进程的退出代码就足够了;你不必阅读它的输出 .

    来自ping(8) - Linux man page

    如果ping根本没有收到任何回复数据包,它将以代码1退出 . 如果指定了数据包计数和截止时间,并且在截止时间到达之前收到的数据包数量少于它,则它也将以代码1退出在其他错误上,它以代码2退出 . 否则它以代码0退出 . 这使得可以使用退出代码来查看主机是否处于活动状态 .

    默认情况下,Linux下运行 ping 直到您停止它 . 但是,您可以使用 -c X 选项仅发送X数据包,并使用 -w X 选项将整个进程的超时设置为X秒 . 这样您就可以限制ping运行所需的时间 .
    下面是使用 QProcess 在Windows上运行ping程序的工作示例 . 对于Linux,您必须相应地更改ping选项(例如 -n-c ) . 在该示例中,ping运行最多X次,其中X是您为 Ping 类构造函数提供的选项 . 只要这些执行中的任何一个以退出代码0(表示成功)返回,就会发出 result 信号,其值为true . 如果没有执行成功,则发出 result 信号,其值为false .

    #include <QCoreApplication>
    #include <QObject>
    #include <QProcess>
    #include <QTimer>
    #include <QDebug>
    
    
    class Ping : public QObject {
    
        Q_OBJECT
    
    public:
    
        Ping(int count)
        : QObject(), count_(count) {
    
            arguments_ << "-n" << "1" << "example.com";
    
            QObject::connect(&process_,
                             SIGNAL(finished(int, QProcess::ExitStatus)),
                             this,
                             SLOT(handlePingOutput(int, QProcess::ExitStatus)));
        };
    
    public slots:
    
        void handlePingOutput(int exitCode, QProcess::ExitStatus exitStatus) {
            qDebug() << exitCode;
            qDebug() << exitStatus;
            qDebug() << static_cast<QIODevice*>(QObject::sender())->readAll();
            if (!exitCode) {
                emit result(true);
            } else {
                if (--count_) {
                    QTimer::singleShot(1000, this, SLOT(ping()));
                } else {
                    emit result(false);
                }
            }
        }
    
        void ping() {
            process_.start("ping", arguments_);
        }
    
    signals:
    
        void result(bool res);
    
    private:
    
        QProcess process_;
        QStringList arguments_;
        int count_;
    };
    
    
    class Test : public QObject {
    
        Q_OBJECT
    
    public:
        Test() : QObject() {};
    
    public slots:
        void handle(bool result) {
            if (result)
                qDebug() << "Ping suceeded";
            else
                qDebug() << "Ping failed";
        }
    };
    
    
    int main(int argc, char *argv[])
    {
        QCoreApplication app(argc, argv);
    
        Test test;
        Ping ping(3);
        QObject::connect(&ping,
                         SIGNAL(result(bool)),
                         &test,
                         SLOT(handle(bool)));
    
        ping.ping();
        app.exec();
    }
    
    #include "main.moc"
    

相关问题