Qt编程8:QProcess的简单使用一(调用外部应用程序)

外部程序以timer.exe为例

 

QProcess启动外部程序的方式常用的有三种:

    void start(const QString &program, const QStringList &arguments, OpenMode mode = ReadWrite);
    void start(const QString &program, OpenMode mode = ReadWrite);
    
    static int execute(const QString &program, const QStringList &arguments);
    static int execute(const QString &program);
    
    static bool startDetached(const QString &program, const QStringList &arguments, const QString &workingDirectory,
                              qint64 *pid = 0);
    static bool startDetached(const QString &program, const QStringList &arguments);
    static bool startDetached(const QString &program);

  start()与startDetached()函数为非阻塞函数。

 

1、例如使用start调用之前写的timer.exe

        pro = newQProcess(this);

    pro->start("timer.exe");
    qDebug() << tr("主程序继续运行");
    qDebug() << tr("-----------------------");

结果显示:timer.exe程序运行了以及qDebug()输出:


 

通常与start()函数结合使用的两个函数(是阻塞函数):

waitForStarted():等待程序启动,超时时间为30秒(可以自己设置等待时间)。如果程序启动成功返回true,启动超时或启动失败返回false。

waitForFinished():等待程序结束,超时时间为30秒(可以自己设置等待时间)。如果在等待时间timer.exe程序结束,则返回true,超时返回false。

    qDebug() << tr("-------------主程序运行中-----------");
    pro->start("timer.exe");
    if(pro->waitForStarted(12))
    {
        qDebug() << tr("timer.exe启动成功");

        //等待外部程序结束,如果在给定的时间内关闭外部程序,返回为真,超时返回false
        if(pro->waitForFinished(10000))
            qDebug() << tr("timer.exe程序被关闭");
        else
            qDebug() << tr("timer.exe程序在规定时间内没有被关闭");
    }
    qDebug() << tr("------------主程序继续运行-----------");

 

//在制定时间10秒内timer.exe没有被关闭

//timer.exe应用被关闭

 

2、 使用pro->execute("timer.exe");则只能运行timer.exe应用,主程序则被阻塞在此处,知道timer.exe结束。

 //不做多的解释

3、通常情况下,使用start()函数调用外部程序,当前程序被关闭之后,外部程序也会被关闭,因此引入函数startDetached()。

     执行成功返回true,否则返回false。

   qDebug() << tr("-------------主程序运行中-----------");
    if(pro->startDetached("timer.exe")
    {
        qDebug() << tr("外部程序timer.exe运行成功");
        close();                //关闭主程序
    }
   qDebug() << tr("------------主程序继续运行-----------");    //不会被执行

   执行结果为:timer.exe正常启动,主程序关闭。

4、当外部程序存在空格或者汉字时,以上三个函数无法使用一个参数执行外部程序,需要传入第二个参数(外部程序如果不带参数)。

QString  program = tr("time 进程/timer.exe");
//"time 进程"文件夹
pro->start(program,QStringList());

pro->execute(program,QStringList());

pro->startDetached(program,QStringList())


 

  • 5
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值