#!/bin/sh set -eu if [ "$#" -lt 2 ] then echo Usage: `basename $0` " ..." exit 1 fi limit="$1" shift cgname="limitmem_$$" echo "limiting memory to $limit (cgroup $cgname) for command $@" cgm create memory "$cgname" >/dev/null cgm setvalue memory "$cgname" memory.limit_in_bytes "$limit" >/dev/null # try also limiting swap usage, but this fails if the system has no swap cgm setvalue memory "$cgname" memsw.limit_in_bytes "$limit" >/dev/null 2>&1 || true # spawn subshell to run in the cgroup set +e ( set -e cgm movepid memory "$cgname" `sh -c 'echo $PPID'` > /dev/null exec "$@" ) # grab exit code exitcode=`echo $?` set -e echo -n "peak memory used: " cgm getvalue memory "$cgname" memory.max_usage_in_bytes | tail -1 | cut -f2 -d\" cgm remove memory "$cgname" >/dev/null exit $exitcode