我使用ctypes模块和WinAPI通过PID查找进程名称。
我一直在查看使用C / C ++编写的this示例,除了我szExeFile
的大小为每个进程为0的事实外,它都在工作。在使用此API时我是否遗漏了某些内容?
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)
PROCESSENTRY32
的结构定义:
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
答案 0 :(得分:2)
你的遗失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 BOOL
中是int
的宏,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);
}