All this script does is take certain field output from the ipcs command and then iterate through it to determine if the memory is still actively in use by a process or if it it can safely be purged. I recommended testing this out with the $memclean line commented out to gain a good understanding before you remove the comment and allow the cleanup (#$memclean = `ipcrm -m $shmem`;). This script was tested on Solaris 10.
#!/usr/bin/perl
@sms = `ipcs -pm|grep "^m"|awk {'print \$2":"\$7":"\$8'}`;
foreach $sms (@sms) {
chomp($sms);
($shmem,$cpid,$lpid) = split(/:/,$sms);
$cpids=` ps -ef|grep $cpid|grep -v grep >/dev/null 2>&1;echo \$?`;
$lpids=` ps -ef|grep $lpid|grep -v grep >/dev/null 2>&1;echo \$?`;
chomp($cpids,$lpids);
if (($cpids eq "1") && ($lpids eq "1")) {
$message = "Memory can be reclaimed";
#$memclean = `ipcrm -m $shmem`;
} else {
$message = "Memory active";
}
print "$shmem - $cpid - $lpid - $cpids - $lpids - $message\n";
}
The output from the script will look similar to the following:
# perl mem_clean.pl
587203562 - 10885 - 17891 - 0 - 0 - Memory active
922746991 - 9728 - 10885 - 0 - 0 - Memory active
150995435 - 9728 - 10885 - 0 - 0 - Memory active
150995432 - 9728 - 17891 - 0 - 0 - Memory active
150995398 - 17421 - 17891 - 1 - 0 - Memory active
150995396 - 13421 - 13891 - 1 - 1 - Memory can be reclaimed
150995387 - 9728 - 10885 - 0 - 0 - Memory active
150995382 - 9728 - 10885 - 0 - 0 - Memory active
150995380 - 9728 - 10885 - 0 - 0 - Memory active
150995379 - 9728 - 10885 - 0 - 0 - Memory active
150995377 - 9728 - 17891 - 0 - 0 - Memory active
150995374 - 9728 - 17891 - 0 - 0 - Memory active
150995371 - 9727 - 10886 - 1 - 0 - Memory active
117440821 - 9728 - 10885 - 0 - 0 - Memory active
117440819 - 9728 - 10885 - 0 - 0 - Memory active#