通过一个进程关闭另外一个进程的时候,一般的做法就是枚举系统打开的所用进程的标识符(PID),使用OpenProcess函数获得进程的句柄,该函数可以通过第一个参数来设置句柄的新的访问权限(不清楚句柄是不是和原来的一模一样?有待证明和学习),比如如果打开的句柄不具备终止句柄的权限,直线终止进程操作会失败,返回的错误代码为5(意思为拒绝访问)。通过获得的句柄就可以获得进程名字(通过GetModuleBaseName函数),通过比对进程名字就可以获得我们指定要关闭的进程。注:要使用closeHandle函数来削减进程计数器。
#include <windows.h> #include <Psapi.h> #include <iostream> #include <tchar.h> using std::cout; using std::endl; HANDLE hDesProcess = NULL; //根据进程的名字(image name)来查找该进程是否是打开的 bool FindProcess( LPCTSTR lpszProcessName ) { DWORD dwProcessIdentify[MAX_PATH] = { 0 }; DWORD dwTrueBytes = 0; HANDLE hProcess = NULL; if ( !EnumProcesses( dwProcessIdentify, MAX_PATH*sizeof(DWORD), &dwTrueBytes )) { cout << "enum process fail " << endl; return false; } int nProcessNum = dwTrueBytes/sizeof(DWORD); HMODULE hModuleInProcess[MAX_PATH] = { 0 }; DWORD dwModuleBytes = 0; TCHAR moduleBaseName[MAX_PATH] = { 0 }; for ( int nIndex = 0; nIndex < nProcessNum; ++nIndex ) { hProcess = OpenProcess( PROCESS_ALL_ACCESS, false, dwProcessIdentify[nIndex] ); // if ( hProcess == NULL ) // { // continue; // } // memset( hModuleInProcess, 0, MAX_PATH*sizeof(HMODULE)); // dwModuleBytes = 0; // if ( !EnumProcessModules( hProcess, hModuleInProcess, MAX_PATH*sizeof(HMODULE),&dwModuleBytes )) // { // cout << "Enum modules in process failed " << endl; // DWORD dwErrorCode = GetLastError(); // //return false; // continue; // } //int nModulesNumInProcess = dwModuleBytes/sizeof(DWORD); memset( moduleBaseName, 0, MAX_PATH*sizeof(TCHAR)); //for ( int nModuleIndex = 0; nModuleIndex < nModulesNumInProcess; ++nModuleIndex ) { GetModuleBaseName( hProcess, NULL,moduleBaseName,MAX_PATH ); if ( !_tcscmp( moduleBaseName, lpszProcessName)) { cout << "查找的进程存在" << endl; hDesProcess = hProcess; return true; } } } return false; } const LPCTSTR lpszProcessName = _T("DriveTheLife.exe"); int main() { if ( !FindProcess( lpszProcessName )) { cout << "进程不存在" << endl; return EXIT_FAILURE; } //终止目标进程 UINT unExitCode = 0; if ( hDesProcess != NULL ) { BOOL bRet = TerminateProcess( hDesProcess, unExitCode ); if ( !bRet ) { DWORD dwErrorCode = GetLastError(); cout << "进程终止失败" << endl; } } DWORD dw = WaitForSingleObject( hDesProcess, INFINITE ); switch ( dw ) { case WAIT_OBJECT_0: cout << 1 << endl; break; case WAIT_FAILED: { DWORD dw1 = GetLastError(); cout << 2 << endl; } break ; default: cout << 3 << endl; } return EXIT_SUCCESS; }