PE获取pid


PE结构获取PID号

CreateToolhelp32Snapshot
Process32First
Process32Next

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <stdio.h>
#include <Windows.h>
#include <tlhelp32.h>
DWORD GetProcessIDByName(const char* pName)
{
//内存快照
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
//printf("%p\n\n", hSnapshot);
//判断是否有获取到内存快照
if (INVALID_HANDLE_VALUE == hSnapshot) {
return NULL;
}
//Process32first和next的参数所需要
PROCESSENTRY32 pe = { sizeof(pe) };
//依次循环每个进程,通过strcmp找到所需要的进程,就跳出。
for (BOOL ret = Process32First(hSnapshot, &pe); ret; ret = Process32Next(hSnapshot, &pe)) {
if (strcmp(pe.szExeFile, pName) == 0) {
CloseHandle(hSnapshot);
return pe.th32ProcessID;
}
}
CloseHandle(hSnapshot);
return 0;
}
int main()
{
int pid = GetProcessIDByName("chrome.exe");
printf("%d\n\n", pid);
getchar();
return 0;
}