Get a process descriptor for a process by image name

I need the simplest path from C using Win32 to get the process descriptor of another process by the name of the executable.

In the process I'm looking for, there are no registered window classes. I also know that if it is running, only one instance will work.

+1
source share
1 answer

Use CreateToolhelp32Snapshot , Process32First, and Process32Next to list all processes.

Inside PROCESSENTRY32 you can find the szExeFile member. You can get the process descriptor by calling OpenProcess with the process identifier th32ProcessID inside the same structure.

Once you find the process matching your exe name, you can exit the loop and get the handle.

Note. If you need to list EVERY process no matter what the session is, you must acquire the SE_DEBUG privilege.

At the top of your main call:

 acquirePrivilegeByName(SE_DEBUG_NAME);// SeDebugPrivilege 

And here is the definition of acquirePrivilegeByName :

 BOOL acquirePrivilegeByName( const TCHAR *szPrivilegeName) { HANDLE htoken; TOKEN_PRIVILEGES tkp; DWORD dwerr; if (szPrivilegeName == NULL) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } if (!LookupPrivilegeValue(NULL, szPrivilegeName, &(tkp.Privileges[0].Luid))) return FALSE; tkp.PrivilegeCount = 1; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &htoken)) return FALSE; if (!AdjustTokenPrivileges(htoken, FALSE, &tkp, 0, NULL, NULL) || GetLastError() != ERROR_SUCCESS) // may equal ERROR_NOT_ALL_ASSIGNED { dwerr = GetLastError(); CloseHandle(htoken); SetLastError(dwerr); return FALSE; } CloseHandle(htoken); SetLastError(ERROR_SUCCESS); return TRUE; } //acquirePrivilegeByName() 

In addition to what I said above, there is an example of how to use the above Win32 API here .

+2
source

Source: https://habr.com/ru/post/1334196/


All Articles