Home  >  Article  >  Backend Development  >  How to Get a Process Handle by Name in C ?

How to Get a Process Handle by Name in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-11-23 00:38:11475browse

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:

  • CreateToolhelp32Snapshot creates a snapshot of the current system processes.
  • Process32First and Process32Next iterate through the process list.
  • _strcmpi compares strings case-insensitively.
  • OpenProcess opens the process handle with the specified access rights.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn