Essam Hassan
A pragmatic software engineer, cyber security enthusiast and a Linux geek. I curse at my machine on a daily basis at Google. My views are my own.
2 min read

wtf series - wtf is pstree?

wtf series - wtf is pstree?

This is part of a series of posts explaining cryptic tech terms in an introductory way.

Disclaimer: this series is not intended to be a main learning source. However, there might be follow up posts with hands-on experiments or deeper technical content for some of these topics.

I wrote this mini-blog because of the many people who asked me what does the name of the blog mean. I was surprised because it's something I use on a daily basis and I just assumed every programmer will know it.

pstree is a unix command-line tool that prints tree of processes. Unlike ps, it prints the hierarchy of processes and not only list the processes. If you specify a username as an argument, it trims out any process not owned by that user. The result is usually a list of subtrees of the original tree.

But, what can it do?

let's start with the syntax

pstree [-a, --arguments] [-c, --compact] 
       [-h, --highlight-all, -Hpid, --high‐light-pid pid] [-g] --show-pgids] 
       [-l, --long] [-n, --numeric-sort] [-p, --show-pids] [-s, --show-parents] 
       [-u, --uid-changes] [-Z, --security-context] 
       [-A, --ascii, -G, --vt100, -U, --unicode] [pid, user]

if you do man pstree in your terminal you will find the previous snippet and guide for all the basic functionality of pstree so I'll skip all that and go to a very specific use case where you can benefit from it

#1: You are building a program that forks processes for specific purpose and kill them afterwards. You want to debug the scenarios and see if the forked processes life-cycle is handled correctly

"Meh. You can always use ps" ~ angry commenter

Using pstree you can view the process hierarchy and check that it's deleted correctly without leaving zombie children processes. This is a very common pitfall when you try to fork a process from your main program and then kill it later. Most languages use a basic SIGKILL and in many cases the spawned process dies leaving out orphan processes often called zombie processes

A very simple way for debugging these scenarios is using pstree and grep on the process name during your program execution to make sure the process lifecycle is handled correctly. One way to ensure killing processes correctly is to use setgid and kill the process group containing the forked process and any children processes.

References

Man pstree(1)