Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

Get PID of process


ghost's Avatar
0 0

I'm having problems finding a Windows API that I can use in python ctypes that can return the PID of a service/process if you only know the name of the process. Anyone got any ideas about how I can work around this problem?


ghost's Avatar
0 0

Use FindWindow to get the handle and GetWindowThreadProcessId() to get the pid using the handle.


ghost's Avatar
0 0

I don't think he was looking for the parent PID


ghost's Avatar
0 0

cyb3rl0rd1867 wrote: Use FindWindow to get the handle and GetWindowThreadProcessId() to get the pid using the handle.Not exactly what I was looking for but it helps. This method only worked for me when the process had a open window, not if it was running in the backgroud. I'm going to look into this some more next weekend when I got some spare time.


mike1990's Avatar
Member
0 0

What programming language you coding in?


techb's Avatar
Member
0 0

Here and this code will get you started. The book that the code is for is pretty good too. Gray Hat Python by Justin Seitz.


fuser's Avatar
Member
0 -1

mike1990 wrote: What programming language you coding in?

he did mention earlier. duh.


j4m32's Avatar
Member
0 0

Sorry, first post ever here and I don't have any Python specific knowledge

I'll try and help with some guide line source for C++… with the Win API usually you can enumerate the process list and filter by image name and then find the PID using something like this (sorry it's C++):

(dword) PID;

(char) szExe[256]; //probably fine as a string in Python?

(Handle) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); //This takes a snapshot of the processes at the time of calling the function

(PROCESSENTRY32) procEntry; //This is the structure the snapshots are then stored in

procEntry.dwSize = sizeof( PROCESSENTRY32 ); //just a safety precaution in allocating memory (from what I remember)

Process32First(Handle, &procEntry); //get an entry to start off

//keep going through them until the end of the list
while(Process32Next(Handle, &procEntry) != false){
//...
//code here to do stuff to match the process you're after, probably matching by a specific image name?

szExe = procEntry.szExeFile;
if(strcmp(szExe,"somename.exe") == 0){ //probably ok to just strait compare the strings with == like in PHP?

PID = procEntry.th32ProcessID;

}

//...
}

Sorry I can't really think of anything more general in a code layout…

I hope that helps somehow in getting a PID for your application in Python - without there being an active main window loaded with a handle.

Jim,