49306956



Управление процессами с помощью скриптов bash
Автор Сообщение
clk824 Не на форуме
Админ
*******

Сообщений: 674
Зарегистрирован: 01.2010
Сообщение: #1
Управление процессами с помощью скриптов bash
Есть некий процесс и у него даже известно имя и PID. Необходимо по крону определять что он впал в ступор и долгое время грузит систему без надежды на выздоровление. Получить информация можно с помощью ps:
Код:
ps -AF | grep 21381.*clamd
Дальше нужно распарсить строку и проанализировать полученную информацию.

Хочешь сказать спасибо? Лучше нажми "Мне нравится", +1 или Like!
(Последний раз сообщение было отредактировано 11.04.2011 в 7:43, отредактировал пользователь clk824.)
11.04.2011 7:42
Вебсайт Найти все сообщения Цитировать это сообщение
clk824 Не на форуме
Админ
*******

Сообщений: 674
Зарегистрирован: 01.2010
Сообщение: #2
RE: Управление процессами с помощью скриптов bash
Но проблема в том что ps даёт данные в виде одномоментного состояния, а хотелось бы получить усреднённые параметры процесса за достаточно большой период. Минимум 1 минута.
Поэтому смотрим в сторону пакетного режима работы top.
Код:
top -b -p 21381

Хочешь сказать спасибо? Лучше нажми "Мне нравится", +1 или Like!
11.04.2011 7:59
Вебсайт Найти все сообщения Цитировать это сообщение
clk824 Не на форуме
Админ
*******

Сообщений: 674
Зарегистрирован: 01.2010
Сообщение: #3
RE: Управление процессами с помощью скриптов bash
Нагуглил подходящий скрипт, правда не тестировал ещё. Заточен под линукс, используется /proc:
Код:
#!/bin/bash
#
# Process control
#
# This shell-script watch that <process> doesn't pass the <limit> of % cpu usage
# If it does, the script kills that process and finish
#
# For linux kernel 2.6.x
# v.0.1 sept-2007
#
# Author: Miguel Angel Molina Molina
# Licence: GPL v.2

# Parameter check
# [debug] parameter is optional and can be anything. If it exists, the script produces output to the screen for debugging purposes.
if [ $# -lt 2 -o $# -gt 3 ];
then
  echo "Usage: `basename $0` <process> <limit> [debug]"
  exit -1
fi

# [debug] exists?
if [ $# -eq 3 ];
then
  debug="yes"
else
  debug=""
fi

procpid=`pidof $1`
typeset -i limit=$2

# process existence check
if [ -z "$procpid" ];
then
  echo "Process: $1 doesn't exists"
  exit -1
fi

# limit check
if [ $limit -lt 1 -o $limit -gt 99 ];
then
  echo "Limit must be between 1 and 99"
  exit -1
fi

typeset -i hits=0

while [ 1 ]
do
  # Get usage cpu time
  typeset -i cputime=`cat /proc/uptime | cut -f1 -d " " | sed 's/\.//'`
  # process pid check
  if [ ! -f /proc/${procpid}/stat ];
  then
    echo "Process doesn't exists: ${procpid}"
    exit -1
  fi
  # Get process usage cpu time
  typeset -i proctime=`cat /proc/${procpid}/stat | awk '{t = $14 + $15;print t}'`
  # wait 5 seconds
  sleep 5
  # get usage cpu time, again
  typeset -i cputime2=`cat /proc/uptime | cut -f1 -d " " | sed 's/\.//'`
  # get process usage cpu time, again
  typeset -i proctime2=`cat /proc/${procpid}/stat | awk '{t = $14 + $15;print t}'`
  # calculate process usage cpu time over total usage cpu time as percentage
  typeset -i cpu=$((($proctime2-$proctime)*100/($cputime2-$cputime)))
  [ ! -z $debug ] && echo "Process $1, with pid: $procpid, is wasting: $cpu% of cpu"
  # limit exceed check
  if [ $cpu -gt $limit ];
  then
    # Count the excess
    let hits+=1
    if [ $hits = 1 ];
    then
      times="time"
    else
      times="times"
    fi
    [ ! -z $debug ] && echo "Process $1 has exceeded the limit: $limit ($cpu) $hits $times ..."
    # If hits are greater than 10, kill the process
    if [ $hits -gt 10 ];
    then
      echo -n "Killing process: $procpid ... "
      kill $procpid
      # wait until process die
      sleep 1
      # check if process has died
      if [ -z "`pidof $1`" ];
      then
        echo "Done."
      else
        echo "Can't kill the process."
      fi
      echo "Finished."
      exit 0
    fi
  else
   # if no limit exceed, reset hit counter
   let hits=0
  fi
done

Хочешь сказать спасибо? Лучше нажми "Мне нравится", +1 или Like!
13.04.2011 8:16
Вебсайт Найти все сообщения Цитировать это сообщение
Создать ответ