[BBLISA] To kill a process tree

Edward Ned Harvey bblisa3 at nedharvey.com
Fri Apr 3 09:47:39 EDT 2009


> You didn't mention which OS you're using.  You may want to see if
> "pgrep/pkill" is available.
> 
> e.g. pkill -SIGTSTP -P ppid

Now that you mention it - you're right.  This is RHEL 4.  Yes I do have
pkill, however, "pkill -P" only matches one level deeper than the named pid.
Doesn't kill the whole process tree - just the immediate children of a pid,
not all of its descendents.

For anyone who's interested, I wrote a script in python to recursively
identify all the descendents of a given pid:

#!/usr/bin/python
import re,commands,sys
processlist=[]

def searchforchildrenof(pid):
  searchfor(pid)
  print ""

def searchfor(pid):
  sys.stdout.write(pid+" ")
  for process in processlist:
    if ( process[1] == pid ):
      searchfor(process[0])

def main():
  if len(sys.argv) != 2:
    print "Displays a list of all the child PIDs that came from a specified
PID"
    print "Usage: "+sys.argv[0]+" pid"
    sys.exit(0)
  oneOrMoreSpaces = re.compile(' +')
  justOneSpace = ' '

  # The "ps" command will give output like this:
  #    PID   PPID
  #     1     0
  #     2     1
  #     ...
  # So when we do the split(), we get the following:
  #    ['PID', 'PPID', '1', '0', '2', '1', ... ]
  # So when we parse this, we casually ignore [0] and [1]
  data = commands.getoutput('ps -e -o "%p%P"').split()

  for i in range(2,len(data),2):
    # data[i] is the PID, and data[i+1] is the PPID
    processlist.append( [data[i],data[i+1]] )

  searchforchildrenof(sys.argv[1])

if __name__ == "__main__" :
  main()




More information about the bblisa mailing list