Link to home
Start Free TrialLog in
Avatar of pb_india
pb_india

asked on

Kill a process

How can I kill a process (exe) in C++. Example say notepad.exe is running and I can see it in process viewer. I need to kill or terminate this process using c++.  I only have the name of the exe/process.

Also I need to restart the process later.

I can use TerminateProcess by I don't know how to get the handle of the process.

Pankaj
Avatar of InteractiveMind
InteractiveMind
Flag of United Kingdom of Great Britain and Northern Ireland image

Avatar of kjpus
kjpus

I give you an example of the code that I use to do the same thing.

----------------------------start-------------------------------

BOOL killResult = FALSE;

// Get a handle to the process
HANDLE hProcess = OpenProcess( PROCESS_TERMINATE, FALSE, procPID );
            
//Kill the process...
killResult = TerminateProcess( hProcess, 0 );

----------------------------stop-------------------------------

These are the lines that do what you want. The rest of the code is more than obvious so I don't write it here.

Hope to have helped

Bakos
I forgot to mention that in function OpenProcess() the 3rd argument (procPID) is the PID of the process. So you have to get the process's ID. That is not a difficult thing to do...

Bakos
Avatar of pb_india

ASKER

I am doing exactly the same three steps;
But when I do:
lpfGetModuleBaseName( hProc, hMod, szName,
                               sizeof(szName)/sizeof(TCHAR) );

I get garbage for szName. I am not sure why? When the process is found, the szName should give me name of process but I get garbage and hence it fails to terminate the process.
Again,

why don't you try to take the processe's handle using its PID? It works 100% and you will do your job. The way is described in my earlier post

Bakos
Like I said, I am using PID and all the steps you mentioned:

// First, get a handle to the process
          hProc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,FALSE,aiPID[dwIndex]);
          // Now, get the process name
          if (hProc)
            {
            if (lpfEnumProcessModules(hProc, &hMod, sizeof(hMod), &dwCbneeded))
            {
                  lpfGetModuleBaseName( hProc, hMod, szName,
                               sizeof(szName)/sizeof(TCHAR) );
Does it matter if my project is under unicode ?
ASKER CERTIFIED SOLUTION
Avatar of x_bakos
x_bakos
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial