Retrieving Process Handle by Name in C
In C , you may encounter situations where you need to manipulate a process based on its name. For example, you might want to terminate a process known as "example.exe" without relying on window handles. This question delves into this specific scenario and presents a solution.
To retrieve the process handle by its name, we can leverage the Windows API functions CreateToolhelp32Snapshot and Process32Next. Here's a code snippet that demonstrates this approach:
#include <cstdio> #include <windows.h> #include <tlhelp32.h> int main() { // Create a snapshot of running processes HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // Iterate over the processes PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { // Check if this is the process we want if (strcmp(entry.szExeFile, "example.exe") == 0) { // Open a handle to the process HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); // Perform desired operations on the process CloseHandle(hProcess); // Close the handle } } } CloseHandle(snapshot); // Close the snapshot handle return 0; }
This solution will iterate through all running processes and compare their executable names with "example.exe". Once a match is found, a handle to that process is obtained and can be used to perform operations such as termination (via TerminateProcess).
Note: If you plan to use PROCESS_ALL_ACCESS in OpenProcess, you might need to elevate your process's privileges by enabling the SE_DEBUG_NAME privilege. Code to do this is shown below:
void EnableDebugPriv() { // Enable debug privilege HANDLE hToken; LUID luid; TOKEN_PRIVILEGES tkp; OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken); LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid); tkp.PrivilegeCount = 1; tkp.Privileges[0].Luid = luid; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL); CloseHandle(hToken); }
The above is the detailed content of How Can I Retrieve a Process Handle by Name in C ?. For more information, please follow other related articles on the PHP Chinese website!