C ++ Process detection, process path discovery, and process Shutdown (2)
The functions used in the previous chapter are complex. This chapter uses the GetModuleFileNameEx function based on the process ID to obtain the process path.
# Include "stdafx. h "# include <windows. h> # include "stdio. h "# include <tlhelp32.h> # include" Psapi. h "int _ tmain (int argc, _ TCHAR * argv []) {int num = 0; TCHAR exe_name [20] = _ T (" notepad1_cmd.exe "); // process name to be queried TCHAR pszFullPath [MAX_PATH]; PROCESSENTRY32 pe32; // HANDLE hProcessSnap structure used to store process information =: createconlhelp32snapshot (TH32CS_SNAPPROCESS, 0 ); // create process snapshot pe32.dwSize = sizeof (pe32); if (hProcessSnap = INVALID_HANDLE_VALUE) {printf ("Createconlhelp32snapshot failed! \ N "); return-1;} BOOL bMore =: Process32First (hProcessSnap, & pe32); // obtain the first process information to the pe32 struct while (bMore) {printf ("name is: % ls \ n", pe32.szExeFile); printf ("num is: % d \ n", num); printf ("ID is: % d \ n ", pe32.th32ProcessID); if (! _ Tcscmp (exe_name, pe32.szExeFile) // locate the process to be searched and end the search {printf ("find the file you want: % ls \ n", pe32.szExeFile); break ;} num ++; bMore =: Process32Next (hProcessSnap, & pe32);} if (! _ Tcscmp (exe_name, parameters) {HANDLE hProcess = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID); TCHAR pBuffer [MAX_PATH + 1]; GetModuleFileNameEx (hProcess, NULL, pBuffer, MAX_PATH + 1); // directly use the GetModuleFileNameEx function to obtain the process file path printf ("file name is: % ls \ n", pBuffer); HANDLE hprocess = :: openProcess (PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID); if (hprocess! = NULL) {: TerminateProcess (hprocess, 0); // close the process printf ("I have close the process you choose! \ N ");: CloseHandle (hprocess) ;}} CloseHandle (hProcessSnap); getchar (); // Let the program have input, return 0 at the end ;}