Posted By

ttscoff on 01/27/09


Tagged

Shell Bash nix memory ram


Versions (?)

Guns


 / Published in: Bash
 

I've lost track of who to credit this to. I apologize to the original author.

  1. #!/bin/sh
  2. # -- guns
  3. #
  4. # Purge inactive memory with rapid i/o
  5. #
  6. # 26 November 2007
  7. # 'killall $command' is still printing to the terminal
  8.  
  9. # declare variables
  10. before=
  11. after=
  12. memPurged=
  13. pageSize=
  14. pagesPurged=
  15. timeout=15 # in seconds
  16. command="du /"
  17.  
  18. showUsage="Usage: $(basename $0) [-h] [-t seconds] [-c \"command\"]"
  19.  
  20. function printError()
  21. {
  22. echo >&2 $showUsage
  23. echo >&2
  24. echo >&2 "See '$(basename $0) -h' for more details."
  25. }
  26.  
  27. function printHelp()
  28. {
  29. echo "Purge inactive memory with rapid i/o."
  30. echo
  31. echo $showUsage
  32. echo
  33. echo "Supported Options"
  34. echo "-----------------"
  35. echo "-t{seconds}\tSet the amount of time for the command to run.
  36. Default"
  37. echo "\t\tis 5 seconds."
  38. echo "-c{\"command\"}\tSet the command to run. Default is 'du /'"
  39. echo "-h\t\tDisplay this help and exit"
  40. }
  41.  
  42. function getMemFree()
  43. {
  44. # the "$3-0" bit is a dirty way to chop the period at the end
  45. vm_stat | awk '/Pages free/ {intMemFree=$3-0; print intMemFree}'
  46. }
  47.  
  48. function getPageSize()
  49. {
  50. vm_stat | awk '/page size/ {print $8}'
  51. }
  52.  
  53. # variables in: $timeout and $command
  54. function purgeMem()
  55. {
  56. # print a message
  57. printf "Accessing disk"
  58.  
  59. $command >/dev/null 2>&1 &
  60.  
  61. # give some feedback
  62. for (( i = 0; i < $timeout*2; i++ )); do # Display a dot every half
  63. sleep .5 # second, so multiply $timeout
  64. printf . # by two
  65. done
  66.  
  67. # kill the process; if exited early, this will be a zombie process
  68. killall $command >/dev/null 2>&1 &
  69.  
  70. if [[ $? == 0 ]]; then
  71. echo "stop"
  72. else
  73. echo "runaway process!"
  74. exit 20
  75. fi
  76. }
  77.  
  78. #
  79. # Main
  80. #
  81.  
  82. while getopts ":ht:c:" option; do
  83. case $option in
  84. h ) printHelp; exit;;
  85. t ) timeout=$OPTARG;;
  86. c ) command=$OPTARG;;
  87. \?) echo >&2 "Invalid option!\n"; printError; exit 3
  88. esac
  89. done
  90. shift $(($OPTIND-1))
  91.  
  92. before=$(getMemFree)
  93.  
  94. purgeMem
  95.  
  96. # set variables
  97. after=$(getMemFree)
  98. let pagesPurged=$after-$before
  99. pageSize=$(getPageSize)
  100.  
  101. # calculate and print
  102. let memPurged=($pagesPurged * $pageSize / 2**20)
  103. printf "%d MB purged.\n" $memPurged

Report this snippet  

You need to login to post a comment.