Skip to content

Instantly share code, notes, and snippets.

@mvollrath
Last active Aug 30, 2021
Embed
What would you like to do?
Run command in a temporary cgroup
#!/bin/sh
set -e
MYNAME=$(basename $0)
usage() {
echo "${MYNAME} runs a command in a temporary cgroup with cpu and/or memory limits."
echo "Usage: ${MYNAME} [-c <cpu_shares>] [-m <mem_limit>] [-s <swmem_limit>] [-h] command args..."
exit 1
}
debug_msg() {
if [ "$CGROUP_LOGLEVEL" = "DEBUG" ]; then
echo "${MYNAME}: $@" >&2
fi
}
CGID="${MYNAME}_$(uuidgen)"
CGPATH="cpu,memory:${CGID}"
while getopts ":c:m:s:h" o; do
case "$o" in
c) CPU_LIMIT="$OPTARG";;
m) MEM_LIMIT="$OPTARG";;
s) SWP_LIMIT="$OPTARG";;
h) usage;;
?) break;;
esac
done
shift "$(($OPTIND-1))"
if [ $# -eq 0 ]; then
usage
fi
sudo cgcreate -a $USER:root -t $USER:root -g "${CGPATH}"
cleanup() {
sudo cgdelete "${CGPATH}"
}
trap cleanup EXIT
if [ -n "$CPU_LIMIT" ]; then
debug_msg "setting CPU shares to $CPU_LIMIT"
cgset -r "cpu.shares=$CPU_LIMIT" "$CGID"
fi
if [ -n "$MEM_LIMIT" ]; then
debug_msg "setting memory limit to $MEM_LIMIT"
cgset -r "memory.limit_in_bytes=$MEM_LIMIT" "$CGID"
fi
if [ -n "$SWP_LIMIT" ]; then
debug_msg "setting memory+swap limit to $SWP_LIMIT"
cgset -r "memory.memsw.limit_in_bytes=$SWP_LIMIT" "$CGID"
fi
cgexec --sticky -g "$CGPATH" $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment