2016-07-24 89 views
1

我使用ctypes模塊和WinAPI通過PID查找進程名稱。 我一直在尋找this用C/C++編寫的例子,它的工作原理除了我的szExeFile的大小對於每個進程都是0。我在使用這個API時錯過了什麼?爲PROCESSENTRY32通過PID查找進程名稱

def find_pid_with_name(process_name: str): 
    entry = PROCESSENTRY32() 
    entry.dwSize = sizeof(PROCESSENTRY32) 

    snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, None) 

    if Process32First(snapshot, byref(entry)) == TRUE: 
     while Process32Next(snapshot, byref(entry)) == TRUE: 
      print(libc.wcslen(entry.szExeFile)) 

    CloseHandle(snapshot) 

我的結構定義:

MAX_PATH = 260 
class PROCESSENTRY32(Structure): 
    _fields_ = [ 
     ("dwSize", c_ulong), 
     ("cntUsage", c_ulong), 
     ("th32ProcessID", c_ulong), 
     ("th32DefaultHeapID", POINTER(c_ulong)), 
     ("th32ModuleId", c_ulong), 
     ("cntThreads", c_ulong), 
     ("th32ParentProcessID", c_ulong), 
     ("dwFlags", c_ulong), 
     ("szExeFile", c_wchar * MAX_PATH) 
    ] 

而我的函數的定義:

CreateToolhelp32Snapshot = windll.kernel32.CreateToolhelp32Snapshot 
CreateToolhelp32Snapshot.argtypes = [c_ulong, POINTER(c_ulong)] 
CreateToolhelp32Snapshot.restype = c_ulong 

libc = CDLL("msvcrt") 
libc.wcslen.argtypes = [c_wchar_p] 

Process32First = windll.kernel32.Process32First 
Process32First.argtypes = [c_ulong, POINTER(PROCESSENTRY32)] 
Process32First.restype = c_ubyte 

Process32Next = windll.kernel32.Process32Next 
Process32Next.argtypes = [c_ulong, POINTER(PROCESSENTRY32)] 
Process32Next.restype = c_ubyte 

回答

1

見定義PROCESSENTRY32W

你的是缺少pcPriClassBase

("dwSize", c_ulong), 
("cntUsage", c_ulong), 
("th32ProcessID", c_ulong), 
("th32DefaultHeapID", POINTER(c_ulong)), 
("th32ModuleId", c_ulong), 
("cntThreads", c_ulong), 
("th32ParentProcessID", c_ulong), 
("pcPriClassBase" , c_long),<======= 
("dwFlags", c_ulong), 
("szExeFile", c_wchar * MAX_PATH) 

也可以嘗試FO返回類型和Arg型

Process32First.argtypes = [ c_void_p , POINTER(PROCESSENTRY32) ] 
Process32First.rettype = c_int 

Process32Next.argtypes = [ c_void_p , POINTER(PROCESSENTRY32) ] 
Process32Next.rettype = c_int 

注意,在WinAPI的BOOLint宏,HANDLE以下是void*

C++源代碼,你是一個宏使用缺少第一個條目。它應該使用一個do-while循環。你可以稍後處理。例如:

HANDLE handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 
if (handle) 
{ 
    PROCESSENTRY32 process; 
    process.dwSize = sizeof(PROCESSENTRY32); 
    Process32First(handle, &process); 
    do 
    { 
     std::wcout << process.szExeFile << "\n"; 
    } while (Process32Next(handle, &process)); 
    CloseHandle(handle); 
} 
+0

非常感謝你;並感謝您指出使用do-while循環。 – jacob

相關問題