How to kill a process by process name in Qt

I am writing a Windows desktop application in Qt.
I have the name of 3 processes that, if they work, I want to kill them at the beginning of my application.
What is the best way to do this? (Get the status of the process using the name of the process, and kill it if it opens).

Sample code can help me a lot. Thank!

+5
source share
4 answers

You can use Qprocess for this purpose. At the beginning of your Do application

Qprocess p;
p.start("pkill processname1");
p.waitForFinished();
p.start("pkill processname2");
p.waitForFinished();
p.start("pkill processname2");
p.waitForFinished();

Or you can directly use the system call.

system("pkill processname1");
system("pkill processname2");
system("pkill processname3");

In a Windows environment, you can use the following commands to kill a process

process -k "Process ID"
process -k "Process Name"

You can read more here.

+10
source

Windows taskkill ,

QProcess::execute("taskkill /im <processname> /f");

system("taskkill /im <processname> /f");
+1

QT does not provide an API to kill processes that are not created by your QT project. If you are on Windows, you can try the following code as described here

#include <windows.h>
#include <process.h>
#include <Tlhelp32.h>
#include <winbase.h>
#include <string.h>
void killProcessByName(const char *filename)
{
    HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
    PROCESSENTRY32 pEntry;
    pEntry.dwSize = sizeof (pEntry);
    BOOL hRes = Process32First(hSnapShot, &pEntry);
    while (hRes)
    {
        if (strcmp(pEntry.szExeFile, filename) == 0)
        {
            HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
                                          (DWORD) pEntry.th32ProcessID);
            if (hProcess != NULL)
            {
                TerminateProcess(hProcess, 9);
                CloseHandle(hProcess);
            }
        }
        hRes = Process32Next(hSnapShot, &pEntry);
    }
    CloseHandle(hSnapShot);
}
int main()
{
    killProcessByName("notepad++.exe");
    return 0;
}
0
source

How to run the application

bool ok = QProcess::startDetached("C:\\TTEC\\CozxyLogger\\CozxyLogger.exe");
qDebug() <<  "Run = " << ok;

How to kill an application

 system("taskkill /im CozxyLogger.exe /f");
 qDebug() << "Close";[enter image description here][1]

More details here:

http://sittikron-big-rmutt.blogspot.com/2018/01/qt-start-and-kill.html

0
source

All Articles