[python-win32] Re: How do I get a child's PID, or the whole process tree?

Rogelio Flores rogelio.flores at gmail.com
Mon Mar 7 17:36:36 CET 2005


On Mon, 7 Mar 2005 10:06:01 -0500, Rogelio Flores
<rogelio.flores at gmail.com> wrote:
> Using win32process.CreateProcess, I can get the process handle/pid of
> a process I launch. Now this process launches other processes and they
> in turn launch other processes without using CreateProcess (so I don't
> have their pids), to the point where I know there are at least two
> levels of parent-child processes. Can I get the pids of these
> child/grandchild processes from the parent pid? Alternatively, can I
> kill the parent pid and all its children along with it?
> 
> I've tried creating the process with win32con.CREATE_NEW_PROCESS_GROUP
> and other combinations of flags/arguments but I'm never able to kill
> but the parent process (all the children are left running) and I
> cannot find a way to get the children's pids from the parent pid or
> handle. It seems that win32pdhutil.py has a way to browse through
> process trees, but I'm not able to figure out how (using
> python2.0/win32all144). Is this possible, and if so, how?
> 
> Thanks,
> 
> --
> Rogelio
> 


OK, I found a solution, using win32pdhutil.ShowAllProcesses() as a
template, I can now get all the processes' pids and their parent pids.
The following code snippet prints a table with these three colums:
Process Name  |  PID  |  Parent PID

----------------- begin code ------------
   import win32pdh
   object = 'Process'
   items, instances = win32pdh.EnumObjectItems(None, None, object, 
                                               win32pdh.PERF_DETAIL_WIZARD)
   instance_dict = {}
   for instance in instances:
      try:
         instance_dict[instance] = instance_dict[instance] + 1
      except KeyError:
         instance_dict[instance] = 0
   for instance, max_instances in instance_dict.items():
      for inum in xrange(max_instances+1):
         hq = win32pdh.OpenQuery()
         hcs = []
         for item in ['ID Process', 'Creating Process ID']:
            path = win32pdh.MakeCounterPath((None,object,instance,
                                             None,inum,item))
            hcs.append(win32pdh.AddCounter(hq,path))
         win32pdh.CollectQueryData(hq)
         print "%-15s\t" % (instance[:15]),
         for hc in hcs:
            type,val=win32pdh.GetFormattedCounterValue(hc,win32pdh.PDH_FMT_LONG)
            print "%5d" % (val),
            win32pdh.RemoveCounter(hc)
         print
         win32pdh.CloseQuery(hq)
---------- end code ---------------

All I needed was to realize that one of the "items" returned by
win32pdh.EnumObjectItems() is 'Creating Process ID', which is the
parent pid of a given process.


-- 
Rogelio


More information about the Python-win32 mailing list