Today, I wrote an automatic upgrade program, which downloads the latest version of the client from the server and then terminates the process using TerminateProcess by locating the client process with the following code:
void KillProcess ( CString strproname) {PROCESSENTRY32 pe32;pe32.dwsize = sizeof (PE32); HANDLE Hprocesssnap =:: CreateToolhelp32Snapshot (th32cs_snapprocess, 0); if (Hprocesssnap = = INVALID_HANDLE_VALUE) Return CString str; BOOL bmore =::P Rocess32first (Hprocesssnap, &pe32); CString strprocessname = _t (""); Strproname.makeupper (); while (bmore) {bmore =::P rocess32next (Hprocesssnap, &PE32) ; strprocessname = Pe32.szexefile;strprocessname.makeupper (); if (Strprocessname.find (strproname)! =-1) {HANDLE HDL = OpenProcess (PROCESS_ALL_ACCESS,TRUE,PE32.TH32PROCESSID); TerminateProcess (hdl,0);:: CloseHandle (HPROCESSSNAP); Return;}}::closehandle (HPROCESSSNAP);}
In the win7 above normal, but on the XP system, but found that the upgrade program to terminate the client process failed, followed the code, found that the execution
<pre name= "code" class= "CPP" >openprocess (PROCESS_ALL_ACCESS,TRUE,PE32.TH32PROCESSID)
Failure, error code 5, Access denied,
Later on the Internet query, and finally found that because of the permissions problem, and found a piece of code
BOOL Enabledebugprivilege () { HANDLE htoken; BOOL Fok=false; if (OpenProcessToken (GetCurrentProcess (), Token_adjust_privileges,&htoken)) { token_privileges tp; Tp. Privilegecount=1; Lookupprivilegevalue (NULL,SE_DEBUG_NAME,&TP. Privileges[0]. LUID); Tp. Privileges[0]. attributes=se_privilege_enabled; AdjustTokenPrivileges (htoken,false,&tp,sizeof (TP), null,null); Fok= (GetLastError () ==error_success); CloseHandle (Htoken); } return fOk;}
Tested and perfectly solved.
Now post the full code:
void KillProcess ( CString strproname) {PROCESSENTRY32 pe32;pe32.dwsize = sizeof (PE32); HANDLE Hprocesssnap =:: CreateToolhelp32Snapshot (th32cs_snapprocess, 0); if (Hprocesssnap = = INVALID_HANDLE_VALUE) Return CString str; BOOL bmore =::P Rocess32first (Hprocesssnap, &pe32); CString strprocessname = _t (""); Strproname.makeupper (); while (bmore) {bmore =::P rocess32next (Hprocesssnap, &PE32) ; strprocessname = Pe32.szexefile;strprocessname.makeupper (); if (Strprocessname.find (strproname)! =-1) {HANDLE HDL = OpenProcess (PROCESS_ALL_ACCESS,TRUE,PE32.TH32PROCESSID); if (!HDL) {enabledebugprivilege (); HDL = OpenProcess ( PROCESS_ALL_ACCESS,TRUE,PE32.TH32PROCESSID);} TerminateProcess (hdl,0);:: CloseHandle (HPROCESSSNAP); Return;}}::closehandle (HPROCESSSNAP);}
TerminateProcess Terminate process failed