Qt 开启进程,查找进程,关闭进程

#include
#include


1, 开启进程

QString path = qApp->applicationDirPath() + "/../../tools/redis/redis-server.exe";
QStringList args;
bool ret = QProcess::startDetached(path);
if (!ret)
{
QMessageBox::warning(this, QStringLiteral("错误"), QStringLiteral("redis服务启动失败!"));
}
else
{
qDebug() << QStringLiteral("服务进程启动, 进程pid:") << m_pid;
}

//程序退出时, 关闭redis服务
DWORD pid;
bool ret = FindProcess("redis-server.exe", pid);
if (ret)
{
KillProcess(pid);
}



2,查找进程

//查找进程
bool FindProcess(const char * name,  DWORD &pid)
{
int i = 0;
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(pe32);
HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE)
{
i += 0;
}
bool bMore = ::Process32First(hProcessSnap, &pe32);
while (bMore)
{
LPTSTR pf = (LPTSTR)(LPCTSTR)pe32.szExeFile;
char *pFileName = (char *)malloc(2 * wcslen(pf) + 1);
wcstombs(pFileName, pf, 2 * wcslen(pf) + 1);
//printf (" 进程名称:%s \n", pe32.szExeFile);  
if (stricmp(name, pFileName) == 0)
{
i += 1;
pid = pe32.th32ProcessID;
return true;

}
bMore = ::Process32Next(hProcessSnap, &pe32);
}
if (i > 0){           //大于1,排除自身  
return true;
}
else{
return false;
}
}


3,关闭进程

//关闭进程
BOOL KillProcess(DWORD ProcessId)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, ProcessId);
if (hProcess == NULL)
return FALSE;
if (!TerminateProcess(hProcess, 0))
return FALSE;
return TRUE;
}



你可能感兴趣的:(qt,C++)