Here, for example, the dumbest approach. We will not go into details: how correct it is, whether we will bring down the system, etc.
#!/bin/sh while [ 1 ] do # получаем %памяти, имя процесса, его PID и юзера: ps axo %mem,comm,pid,euser | \ # если процесс занимает больше 10% - убиваем: awk -F' ' '{ \ if( $1 > 10 ) { \ printf( "KILL %s:%s - %s\n",$2,$4,$3 ); \ system( "kill -9 " $3 ); \ } \ }' sleep 10 done
You can go further: first determine how much memory is free, and start killing only if there is less than some limit left. Enter a list of unkillable exceptions, calculate not %% in general, but from occupied / free memory, etc. For example:
#!/usr/bin/perl use Modern::Perl; # свободной памяти больше - не дёргаемся: use constant MIN_FREE_MEM => 40; # сколько %% памяти разрешается занимать процессу: use constant MAX_PROCESS_MEM => 10; use constant SLEEP_DELAY => 10; # будем использовать смотреть точное совпадение, # но можно и под регекспы переделать my %excludes = ( 'init' => 1, 'eclipse' => 1, ); while (1) { # элементы массива будут такими: # 0 1 2 3 # [ %памяти, имя процесса, его PID, юзер ] my @pinfo = map { s/^\s+|\s+$//g; [ split /\s+/ ]; } split "\n", `ps axo %mem,comm,pid,euser`; # удалить первую строку с заголовком shift @pinfo; my $free = 100.0; $free -= $_->[0] for @pinfo; # теперь мы знаем сколько %% памяти свободно if ( $free < MIN_FREE_MEM ) { # пропускаем исключения: next if $excludes{ $_->[1] }; for (@pinfo) { if ( $_->[0] > MAX_PROCESS_MEM ) { say "Killing process $_->[2]:$_->[1]:$_->[3] ($_->[0]%)"; kill '-KILL', $_->[2]; } } } sleep SLEEP_DELAY; }
ps -auxf | sort -nr -k 3 | head -10:ps -auxf | sort -nr -k 3 | head -10ps -auxf | sort -nr -k 3 | head -10ps -auxf | sort -nr -k 3 | head -10are the 10 processes that eat the most memory at the moment. Set the maximum value, if it is exceeded - kill. The script is written on the knee faster than the comment :) Another question is how justified it will be ... - PinkTux