1# Copyright 2013 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5from collections import defaultdict
6
7
8def GetChildPids(processes, pid):
9  """Returns all child processes of |pid| from the given |processes| list.
10
11  Args:
12    processes: A tuple of (pid, ppid, state) as generated by ps.
13    pid: The pid for which to get children.
14
15  Returns:
16    A list of child pids.
17  """
18  child_dict = defaultdict(list)
19  for curr_pid, curr_ppid, state in processes:
20    if 'Z' in state:
21      continue  # Ignore zombie processes
22    child_dict[int(curr_ppid)].append(int(curr_pid))
23  queue = [pid]
24  child_ids = []
25  while queue:
26    parent = queue.pop()
27    if parent in child_dict:
28      children = child_dict[parent]
29      queue.extend(children)
30      child_ids.extend(children)
31  return child_ids
32