QProcess有一个signal叫做finished,具体定义如下:void QProcess::finished(int exitCode,QProcess::ExitStatus exitStatus) 当进程结束的时候,该signal会被发射出去。exitCode就是进程的退出码,而exitStatus就是退出状态。若在一个系统服务中,想保持另一个进程始终处于运行状态(比如某server),那么就可以connect这个finished信号。详细代码如下:
void keepProcessRunning() { QProcess* p = new QProcess(); QObject::connect(p,&QProcess::started,[](){ qDebug()<<"Notepad.exe started!"; }); //Keep restarting if notepad.exe is finished QObject::connect(p,static_cast<void(QProcess::*)(int,QProcess::ExitStatus)>(&QProcess::finished), [p](intexitCode,QProcess::ExitStatus exitStatus){ qWarning()<<"Notepad.exe was terminated!" <<"Exit code:"<<exitCode<<"Exit status:"<<exitStatus; qWarning()<<"Notepad.exe will restart..."; p->start(); }); p->start("notepad.exe"); }
以上代码中,先连接了started() signal,但这仅仅是为了打印一条语句“Notepad.exe started!”。然后连接了finished signal,其主要动作是再次调用p->start().但是注意,这里的start()是不带参数的。在两次connect结束之后,调用p->start("notepad.exe");以启动笔记本程序。connect中的p->start()之所以没有参数,就是因为在它后面调用的start是有参数的。而再次start的话,是可以不再注明参数的。
