Home > Article > Backend Development > How to Get a Process Handle by Name in C ?
Accessing Process Handles by Name in C
In C , retrieving a process handle by its name is a common task for managing system resources. Here's how you can achieve this:
#include <windows.h> #include <tlhelp32.h> int main(int argc, char *argv[]) { PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { if (_strcmpi(entry.szExeFile, "target.exe") == 0) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); // Perform desired operations here... CloseHandle(hProcess); } } } CloseHandle(snapshot); return 0; }
Note:
If you don't have sufficient privileges (specifically, the "Debug privileges"), you may need to adjust the token privileges using the EnableDebugPriv function:
void EnableDebugPriv() { HANDLE hToken; LUID luid; TOKEN_PRIVILEGES tkp; ... // Adjust token privileges to enable debugging }
The above is the detailed content of How to Get a Process Handle by Name in C ?. For more information, please follow other related articles on the PHP Chinese website!