OpenProcess
The OpenProcess
function opens an existing local process object.
HANDLE WINAPI OpenProcess(
DWORD dwDesiredAccess,
BOOL bInheritHandle,
DWORD dwProcessId
);
Note: You must have appropriate access rights. Some rights require the caller to have the
SeDebugPrivilege
.
Parameters
Parameter | Description |
---|---|
dwDesiredAccess |
Access rights requested for the process object. Combining flags with a logical OR is allowed. |
bInheritHandle |
If non‑zero, the returned handle can be inherited by child processes. |
dwProcessId |
The identifier of the process to be opened. |
Common Access Rights
Flag | Meaning |
---|---|
PROCESS_TERMINATE | Terminate the process. |
PROCESS_CREATE_THREAD | Create a thread in the process. |
PROCESS_VM_OPERATION | Perform memory operations (e.g., VirtualAllocEx). |
PROCESS_VM_READ | Read the process's memory. |
PROCESS_VM_WRITE | Write to the process's memory. |
PROCESS_DUP_HANDLE | Duplicate handles in the process. |
PROCESS_QUERY_INFORMATION | Query certain information about the process. |
PROCESS_SET_INFORMATION | Set certain information about the process. |
SYNCHRONIZE | Wait on the process handle. |
Return Value
If the function succeeds, the return value is a handle to the specified process. If the function fails, the return value is NULL
. To get extended error information, call GetLastError
.
Remarks
- The handle returned by
OpenProcess
must be closed withCloseHandle
when it is no longer needed. - Access rights are checked against the security descriptor of the target process object.
- Attempting to open a system process without sufficient privileges will fail with
ERROR_ACCESS_DENIED
. - Use
PROCESS_ALL_ACCESS
with caution – it may be restricted by the User Account Control (UAC) mechanism.
Example
#include <windows.h>
#include <stdio.h>
int main(void)
{
DWORD pid = 1234; // Replace with target PID
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE, pid);
if (hProcess == NULL) {
printf("OpenProcess failed. Error: %lu\\n", GetLastError());
return 1;
}
// Example: retrieve the process's executable name
wchar_t path[MAX_PATH];
if (GetModuleFileNameExW(hProcess, NULL, path, MAX_PATH))
wprintf(L"Process path: %s\\n", path);
else
printf("GetModuleFileNameEx failed. Error: %lu\\n", GetLastError());
CloseHandle(hProcess);
return 0;
}