4

I'm trying to write a bash script which would log all descendants process information in below format but I have to log the info only when a process has more than six descendants process.

PID PPID Level
10 9 1 (indicates child)
9 8 2 (indicates parent)
8 7 3 (indicates grand parent)
Pstree -ps 10 should display:
dummy1---dummy2---dummy3---dummy4---dummy5---dummy6---dummy7

How to trigger dummy process in above manner?

Frankly I have no idea about bash script, only thing i was able to do was display PID's of a particular user.

while read -r processId;
do
    echo $processId
done <<< "$(ps -u $USER -o pid)"

I need to loop each PID & check if it has more than six descendants but before that I want to manually trigger six descendants process to start & test my script.

1 Answer 1

6

To start a script with seven descendants, you can use something like this:

#!/bin/bash

if [[ "$#" -ne 1 ]]; then
    set -- 7
fi

if [[ "$1" -gt 2 ]]; then
    "$0" "$(($1 - 1))"
else
    sleep 120
fi

or more compactly,

#!/bin/bash

[[ "$#" -ne 1 ]] && set -- 7

[[ $1 -gt 2 ]] && $0 $(($1 - 1)) || sleep 120

If this is given no or too many arguments, it sets its argument to 7. Then as long as its argument is greater than 2, it starts a child running the same script, with a decremented argument. When the argument reaches 2, it runs a two-minute sleep. (The limit is two because the last script and the sleep also count as one each.)

$ ./dummy &
$ pstree -p 1800554
dummy(1800554)───dummy(1800561)───dummy(1800563)───dummy(1800566)───dummy(1800567)───dummy(1800570)───sleep(1800572)

You can request a different number of children by changing the argument:

$ ./dummy 6 &

This can be extended to start multiple children in each “generation”:

#!/bin/bash

[[ "$#" -ne 2 ]] && set -- 1 7

for (( i = 0; i < $1; i++ )); do
[[ $2 -gt 2 ]] && $0 $1 $(($2 - 1)) || sleep 120 &
done
wait

Run it as

./dummy 3 2 &

to start two generations with three children each.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.