- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
#!/bin/bash
######################################################################################
#
# Write a bash script that obtains active processes for the current user,
# breaks them into chains and prints all unique chains containing 3 or more
# PIDs in the following format:
# PID1:PID2:PID3:…:PIDn
# PID:PID:PID:…:PID
# …
# So that each next PID is a parent of the previous PID, the first PID in
# each chain does not have children and the last PID in each chain
# does not have parent.
#
######################################################################################
TEMPFILE="/tmp/$0$$" # file needs to save the process list
# it's really needed to divide columns
# generated 'ps'
# parameters:
# -H - sorts the list as process forest (it lets to find connection between child and parent faster)
# -o - sets the output format
# "%p %P" - thow columns in output: PID and PPID
# -u - sets username
# `whoami` - get the current user name
ps -H -o "%p %P" -u `whoami` > $TEMPFILE
PIDLIST=(`awk '/[0-9]/ {print $1}' $TEMPFILE`) # make an array using the first column
PPIDLIST=(`awk '/[0-9]/ {print $2}' $TEMPFILE`) # and the second
SIZE=${#PIDLIST[*]}
K=0
# bypassing the forest using stack which emulates LINKS array. K is the pointer to stack's top
for (( i=0; i<$SIZE; i++ ))
do
if [[ $K = 0 || ${PPIDLIST[$i]} = ${LINKS[$K-1]} ]] # new tree or new edge in the tree.
then
LINKS[$K]=${PIDLIST[$i]} # push PID to stack
K=`expr $K + 1`
else # the chain is complete.
if [[ $K > 2 ]] # enough size to print the chain
then # reversed formatted output the chain
echo ${LINKS[*]} | awk '{ printf $NF; for (i = NF-1; i > 0; --i) printf ":"$i}'
echo
fi
until [[ $K == 0 || ${PPIDLIST[$i]} == ${LINKS[$K-1]} ]]
do # deleting elements from stack until find a
# parent or tree is end
unset LINKS[$K-1]
K=`expr $K - 1`
done
LINKS[$K]=${PIDLIST[$i]} # push PID to stack
K=`expr $K + 1`
fi
done
rm -rf $TEMPFILE # removing temp file