Advertisement
Guest User

Untitled

a guest
Mar 24th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. #!/bin/sh
  2.  
  3. set -eu
  4.  
  5. if [ "$#" -lt 2 ]
  6. then
  7. echo Usage: `basename $0` "<limit> <command>..."
  8. exit 1
  9. fi
  10.  
  11. limit="$1"
  12. shift
  13.  
  14. cgname="limitmem_$$"
  15. echo "limiting memory to $limit (cgroup $cgname) for command $@" >&2
  16.  
  17. cgm create memory "$cgname" >/dev/null
  18. cgm setvalue memory "$cgname" memory.limit_in_bytes "$limit" >/dev/null
  19. # try also limiting swap usage, but this fails if the system has no swap
  20. cgm setvalue memory "$cgname" memory.memsw.limit_in_bytes "$limit" >/dev/null 2>&1 || true
  21. bytes_limit=`cgm getvalue memory "$cgname" memory.limit_in_bytes | tail -1 | cut -f2 -d\"`
  22.  
  23. # spawn subshell to run in the cgroup
  24. # set +e so a failing child does not prevent us from removing the cgroup
  25. set +e
  26. (
  27. set -e
  28. cgm movepid memory "$cgname" `sh -c 'echo $PPID'` > /dev/null
  29. exec "$@"
  30. )
  31.  
  32. # grab exit code
  33. exitcode=`echo $?`
  34.  
  35. set -e
  36.  
  37. peak_mem=`cgm getvalue memory "$cgname" memory.max_usage_in_bytes | tail -1 | cut -f2 -d\"`
  38. failcount=`cgm getvalue memory "$cgname" memory.failcnt | tail -1 | cut -f2 -d\"`
  39. percent=`expr "$peak_mem" / \( "$bytes_limit" / 100 \)`
  40. echo "peak memory used: $peak_mem ($percent%); exceeded limit $failcount times" >&2
  41.  
  42. cgm remove memory "$cgname" >/dev/null
  43.  
  44. exit $exitcode
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement