Posted on 2010-12-27 20:43
S.l.e!ep.¢% 閱讀(1079)
評論(0) 編輯 收藏 引用 所屬分類:
Unix
#!/usr/bin/perl
?use strict;
?# 打印此腳本使用信息和輸出說明。
?################################################################
?# Output the usage of this perl script
?################################################################
?sub usage
?{
??? print "memmonitor: Monitor system memory usage\n";
??? print "1. if used memory is more than 75% of total memory, memmonitor\n";
??? print "will output one warning message per minites.\n";
??? print "2. if used memory is more than 90% of total momory, memmonitor\n";
??? print "will kill the processes that occupied the most memory untill\n";
??? print "used memory is less than 75% of total memory.\n\n";
??? 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\n";
?}
?# 如果內存使用率大于 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]\n";
??????????? # 發送警告信息給 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
?}