Journal

By Steve Challis

Recent Entries

Archive

RSS/Atom

Home

Projects

@schallis

A Portable Bash Function to List Process Hierarchies

April 15th, 2011 — 0 Comments — Permalink

  • bash
  • script

It can be useful to find the process hierarchy of a particular process when diagnosing a problematic machine. Say for instance you run into a rogue program and want to find out what spawned it before you kill it. The Unix command pstree (or ptree on Solaris) will show you a tree of running processes but is not always available.

Since I ran into this problem recently, I concocted the following recursive function to traverse a process tree to its root from a given pid:

parents(){ :(){                                                                                                                       
          read p n <<<`ps -o ppid,comm -p $1 | awk 'NR>1{print $1,$2}'`;
          echo -e "$1\t$n";
          test $1 -ne 0 && : $p; };
      : $1; }

Let's see it in action:

stevechallis:~$ parents 28311                                                                                                         
28311   /bin/sh
488 /Applications/Emacs.app/Contents/MacOS/Emacs
1   /sbin/launchd
0

Discussion

There are no comments for this post.

Comments on this post have now been closed.

Log in

Powered by Mumblr – a basic Django tumblelog application that uses MongoDB with MongoEngine. Fork it on Github. Designed and developed by Harry Marr and Steve Challis.

Unless otherwise noted, everything here is available under the Creative Commons Attribution-Share Alike 3.0 license. Sharing is fucking cool.

Home / Projects / Recent / Archive / RSS /