Files
homework12/myps.sh

59 lines
2.4 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/bash
# Выводим заголовок
printf "%-20s %-10s %-10s %-10s %-10s %-10s %s\n" "User" "PID" "PPID" "CPU_Time" "Memory" "Status" "Command"
echo "------------------------------------------------------------------------------------------"
# Проходим по всем PID в /proc
for pid in /proc/[0-9]*/; do
pid=$(basename "$pid")
#читаем информацию о процессе
if [[ -f "/proc/$pid/status" ]]
then
#Ищем имя пользователя, от имени которого запущен процесс
userName=$(id -un "$(grep '^Uid:' "/proc/$pid/status" | awk '{print $2}')")
#Получаем роодителя
ppid=$(grep '^PPid:' "/proc/$pid/status" | awk '{print $2}')
#Статус процесса
status=$(grep '^State:' "/proc/$pid/status" | awk '{print $2}' | cut -c1)
#Время использования CPU
cpuTimeSeconds=$(userTime=$(cat /proc/$pid/stat | awk '{print $14}'); systemTime=$(cat /proc/$pid/stat | awk '{print $15}'); echo "$(( (userTime + systemTime) / 100))")
#Переводим в формат М:С
cpuTime=$(date -u -d "@$cpuTimeSeconds" +"%M:%S")
# Получаем использование памяти
memUsage=$(cat /proc/$pid/status| grep VmRSS | awk '{print $2}')
if [[ -z "$memUsage" ]]; then
memUsage="0"
fi
#берем командную строку
cmdLine=""
if [[ -f "/proc/$pid/cmdline" ]]; then
# Читаем cmdLine, заменяем нулевые байты на пробелы
cmdLine=$(tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null | sed 's/ $//')
fi
#Если командная строка пустая, берем имя процесса
if [[ -z "$cmdLine" ]]
then
cmdLine="[$(grep '^Name:' "/proc/$pid/status" | awk '{print $2}')]"
fi
#Укорачиваем до 50 символов
if [[ ${#cmdLine} -gt 50 ]]
then
cmdLine="${cmdLine:0:47}..."
fi
# Выводим информацию
printf "%-20s %-10s %-10s %-10s %-10s %-10s %s\n" \
"$userName" "$pid" "$ppid" "$cpuTime" "$memUsage" "$status" "$cmdLine"
fi
done | sort -n -k2 # Сортируем по PID