メモリの状態を確認し、自動的にKILLプロセス
2176 ワード
#!/usr/bin/perl
use strict;
# 。
################################################################
# Output the usage of this perl script
################################################################
sub usage
{
print "memmonitor: Monitor system memory usage
";
print "1. if used memory is more than 75% of total memory, memmonitor
";
print "will output one warning message per minites.
";
print "2. if used memory is more than 90% of total momory, memmonitor
";
print "will kill the processes that occupied the most memory untill
";
print "used memory is less than 75% of total memory.
";
return 0;
}
usage
my $total_mem;
my $used_mem;
my $next_line = 0;
my @rc;
my $rate;
# $total_mem $used_mem
rc = `vmstat`;
foreach ( @rc ) {
if ( $next_line ) {
my @value = split /\s+/, $_;
$used_mem = @value[3] * 4;
$next_line = 0;
last;
} elsif ( /^.*mem=(\d+)MB$/ ) {
$total_mem = $1 * 1024;
} elsif ( /^.*avm.*$/ ) {
$next_line = 1;
}
}
# vmstat , , 。
if ( $total_mem ) {
$rate = $used_mem / $total_mem;
}
#
if ( $rate > 0.75 ) {
print "Warning: Memory is not enough
";
}
# 0.75, 。
if ( $rate > 0.9 ) {
my $line_count = 0;
my @output = `ps aux | head -1;ps aux | sort -rn +5`;
foreach ( @output ) {
if ( $line_count ) {
my @killed_process = split /\s+/,$_;
print "Warning: Out of memory. Kill process: @killed_process[1]
";
# root , 。
`echo "Process @killed_process[1] has been killed because of unlimited memory \
allocation" | mail -s "Out of memory" root`
`kill -11 @killed_process[1]`;
last;
}
$line_count = $line_count + 1;
}
# 0.9, ps , ,
# 。 0.9
}