0

I will trigger seven dummy descendant processes using below code:

#!/bin/bash

if [[ "$#" -ne 1 ]]; then
    set -- 7 #To set command line argument to 7 when arguments aren't provided
fi

if [[ "$1" -gt 2 ]]; then
    "$0" "$(($1 - 1))" #Execute same script by passing a number(decrementing)
else
    sleep 120
fi

Thus pstree -pc 101 (assuming 101 is pid of first process of above script) will display:

dummy(101)──dummy(102)──dummy(103)──dummy(104)──dummy(105)──dummy(106)──sleep(107)

How do I display the information of the dummy process in below format:

PID PPID Level
107 106 1 (indicates child)
106 105 2 (indicates parent)
105 104 3 (indicates grand parent)
104 103 4
103 102 5
102 101 6
101 100 7

Frankly I do not know Bash scripting. I have just learned how to to display PID'S of a user processes using below command:

ps -u $USER -o user,pid,ppid,lstart,cmd

1 Answer 1

1

Was able to get required information using recursion:

#!/usr/bin/env bash

get_child()
{
  local -i pid=0 ppid=$1 depth=$2 parentId=$3
  echo $ppid $parentId $depth

  while read -r pid; do
    echo $ppid
    ((pid)) && get_child $pid $((depth + 1)) $ppid
  done < <(ps -o pid= --ppid $ppid)
}

get_child $1 0 0

You must log in to answer this question.

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