def kill_procs(child_processes, kill=None, verbose=True, timeout=5,
               close_fds=True):
  child_processes = filter(lambda e: e is not None, child_processes)
  def msg(msg):
    if(verbose):
      sys.stderr.write(msg)

  if kill == None:
    if hasattr(kill_procs,"already_run"):
      kill = True
    else:
      kill = False
      kill_procs.already_run = True

  if len(child_processes) == 0:
    return

  msg(("Killing" if kill else "Terminating") % "%s child controllers...")
  for child in child_processes:
    sig = signal.SIGKILL if kill else signal.SIGTERM
    pgid = os.getpgid(child.pid)
    if pgid == child.pid:
      # if the child is the leader in its process group (happens because of
      # the setsid in popen_filtered below), kill the entire process group.
      # this will take care of spawned children, e.g., the bash process
      # forked when shell=True
      os.killpg(pgid, sig)
    else:
      os.kill(child.pid, sig)

  start_time = time.time()
  last_dot = start_time
  all_dead = []
  while True:
    (child_processes, new_dead) = split_up(lambda child: child.poll() is None, child_processes)
    all_dead += new_dead
    if len(child_processes) == 0:
      break
    if hasattr(time, "_orig_sleep"):
      time._orig_sleep(0.1)
    else:
      time.sleep(0.1)
    now = time.time()
    if (now - last_dot) > 1:
      msg(".")
      last_dot = now
    if (now - start_time) > timeout:
      if kill:
        break
      else:
        msg(' FAILED (timeout)!\n')
        kill_procs(child_processes, kill=True)
        break

  if close_fds:
    for child in all_dead:
      for attr_name in "stdin", "stdout", "stderr":
        if hasattr(child, attr_name):
          try:
            attr = getattr(child, attr_name)
            if attr:
              attr.close()
          except IOError:
            msg("close() called on %s during concurrent operation\n" % attr_name)
          except:
            msg("Error closing child io.\n")
            tb = traceback.format_exc()
            msg(tb)

  if len(child_processes) == 0:
    msg(' OK\n')
dataset/ETHPy150Open ucb-sts/sts/sts/util/procutils.py/kill_procs/swapped operands of `%`