I'm implementing pstree as an assignment,

and I would like to create test tree of processes, but I'm struggling to do so.

I tried to do something like this to create tree of background processes so I can test my script later.

recursive tree of processes


        echo "mine PID is: "$$

        local -i level=$(expr $1 - 1)  # level of recursion

        if [[ $level -gt 0 ]]; then
          echo $level
          childProcess $level &           # we do binary tree
          echo "Process with  PID $! launched"
          childProcess $level &
          echo "Process with  PID $! launched"
          sleep $level
          echo "baf! "$level" pid is: "$$

# create binary tree of depth 4
for (( i = 0; i < 2; i++ )); do
    childProcess 4 &
    echo "running proces no. :"$!

But I would like to echo PID from within of process, and with this I can't.

Another not-working-solution would be this, but it creates processes in "DFS manner".

declare -i level=$1

if [[ $level -gt 0 ]]; then
  sh $0 $(expr $level - 1)  # spawn children
  sh $0 $(expr $level - 1)  # spawn children

  sleep 100;
  echo "level :"$level" process no: "$$

Can anyone tell me how to construct tree of processes which I can acces by PID, and that would be there until I delete them, e.g. by killing oldest process.

1 Answer 1


I'd suggest taking a snapshot of the processes currently running on the system. The absolute minimum that you'd need is each PID and its corresponding PPID:

ps -ax -o pid=,ppid=

This will give you two columns of numbers that could be stored in a file and edited by hand if you want to do so. The benefit of this is that it gives you input for your program from a real running system, and it's easy to produce.

You can then work out the minimal program to read these numbers and output them in a tree-like manner, like

awk -v OFS='\t' '
        ppid[$1] = $2

function print_pid(pid, level) {
        $0 = ""
        $(level+1) = pid

        for (p in ppid)
                if (ppid[p] == pid)
                        print_pid(p, level + 1)


The remaining effort would be to add the actual command names etc. to the output (you will have to ask ps to provide more data), and to decorate the output with simple ASCII graphics.

As far as I know, the pstree utility I have access to actually uses ps to produce its input.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .