Skip to content

Instantly share code, notes, and snippets.

@fl64
Created August 10, 2018 19:56
Show Gist options
  • Save fl64/34849621ea2128c6dfeaec36e14a1eee to your computer and use it in GitHub Desktop.
Save fl64/34849621ea2128c6dfeaec36e14a1eee to your computer and use it in GitHub Desktop.
#!/bin/bash
printf "%5s %-8s %-5s %2s:%02d %s \n" "PID" "TTY" "STAT" "TIME" "COMMAND"
for i in /proc/[0-9]*; do
#read pid cmd state ppid pgrp sid tty_nr tpgid other < $i/stat
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# $pid $cmd $state $ppid $pgrp $sid $tty_nr $tpgid flags minflt cminfflt majflt cmajflt utime stime cutime cstime priority nice
regex='([0-9]*) \((.*)\).* ([DRSTWXZ]+) ([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*) (\-?[0-9]*) ([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*) (\-?[0-9]*) ([0-9]*) ([0-9]*) ([0-9]*)'
read out < $i/stat
#echo $out
if [[ $out =~ $regex ]]; then
major=$((${BASH_REMATCH[7]} >> 8))
minor=$((${BASH_REMATCH[7]} & 0xFF))
#echo "nice: ${BASH_REMATCH[18]} == ${BASH_REMATCH[19]}"
# get TYY name
# major 136-143 - for pts
p_tty=""
state=${BASH_REMATCH[3]}
if [ $major -ge 136 ] && [ $major -le 143 ]; then
# p_tty="pts/"$(ls -lha /dev/pts/ | grep "$major, $minor" | grep -o '[^ ]*$')
p_tty="pts/"$[$minor + $[$major - 136] * 256]
else
if ! [ -e "$(readlink -f /sys/dev/char/$major\:$minor)" ]; then
p_tty="?"
else
p_tty=$(readlink /sys/dev/char/$major\:$minor | grep -o '[^\/]*$')
fi
fi
# process name or cmdline
if [ $(cat $i/cmdline | wc -c) -eq 0 ]; then
# procname="["$( echo $cmd | awk -F '[()]' '{print $2}' )"]"
procname="["${BASH_REMATCH[2]}"]"
else
procname=$( cat $i/cmdline | tr '\0' ' ' )
fi
#TIME
hz=$(getconf CLK_TCK)
t_total_ticks=$((${BASH_REMATCH[14]} + ${BASH_REMATCH[15]}))
t_min=$(( ($t_total_ticks / $hz) / 60 ))
t_sec=$(( ($t_total_ticks / $hz) - $t_min * 60 ))
# < high-priority (not nice to other users)
if [ ${BASH_REMATCH[19]} -gt 0 ] && [ ${BASH_REMATCH[19]} -le 20 ]; then state=$state"N"; fi
if [ ${BASH_REMATCH[19]} -ge -29 ] && [ ${BASH_REMATCH[19]} -lt 0 ]; then state=$state"<"; fi
#L has pages locked into memory (for real-time and custom IO)
locked=$(cat $i/status | grep VmLck: | tr -s ' ' | cut -f 2 -d " ")
if ! [ -z $locked ] && ! [ $locked -eq 0 ];
then state=$state"L"; fi
# state
#s is a session leader
if [ ${BASH_REMATCH[1]} -eq ${BASH_REMATCH[6]} ];
then state=$state"s"; fi
#l is multi-threaded
if [ -d "$i/task" ];
then state=$state"l"; fi
#echo {"pid:"${BASH_REMATCH[1]} "tpgid:"${BASH_REMATCH[8]} }
#+ is in the foreground process group
if [ ${BASH_REMATCH[1]} -eq ${BASH_REMATCH[8]} ];
then state=$state"+"; fi
printf "%5s %-8s %-5s %2s:%02d %s \n" ${BASH_REMATCH[1]} "$p_tty" $state $t_min $t_sec "$procname" | cut -c-$(tput cols)
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment