QProcess启动外部程序的方式常用的有三种:
start()、execute()、startdetached().
start()与startDetached()函数为非阻塞函数。
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);
1、使用start()函数
通常与start()函数结合使用的两个函数(是阻塞函数):
waitForStarted():等待程序启动,超时时间为30秒(可以自己设置等待时间)。如果程序启动成功返回true,启动超时或启动失败返回false。
waitForFinished():等待程序结束,超时时间为30秒(可以自己设置等待时间)。如果在等待时间timer.exe程序结束,则返回true,超时返回false。
比如有个外部程序叫timer.exe
QProcess *pro=new QProcess(this);
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("------------主程序继续运行-----------");
2、使用execute()阻塞模式
使用pro->execute("timer.exe");则只能运行timer.exe应用,主程序则被阻塞在此处,知道timer.exe结束。
3、使用startDetached()模式
通常情况下,使用start()函数调用外部程序,当前程序被关闭之后,外部程序也会被关闭,因此引入函数startDetached()。
执行成功返回true,否则返回false。主程序关闭,外部程序也没被关闭。
4、当外部程序存在空格或者汉字时,以上三个函数无法使用一个参数执行外部程序,需要传入第二个参数(外部程序如果不带参数)。
QString program = tr("time 进程/timer.exe");
//"time 进程"文件夹
pro->start(program,QStringList());
pro->execute(program,QStringList());
pro->startDetached(program,QStringList())
5、如果外部程序自带配置文件ini或者其他,这个配置文件必须和主程序在一起。
6、使用QProcess杀进程
QProcess p;
QString c = "taskkill /im timer.exe /f";
p.execute(c);
p.close();