Skip to content

Instantly share code, notes, and snippets.

@Prince781
Created December 26, 2023 20:46
Show Gist options
  • Save Prince781/88090deeedd884fcdc88ba6eddeadd45 to your computer and use it in GitHub Desktop.
Save Prince781/88090deeedd884fcdc88ba6eddeadd45 to your computer and use it in GitHub Desktop.
launch program with memory bounds
limit_process() {
if (( $# < 2 )); then
echo "Usage: $0 size command ..."
return 1
fi
size=$1
command=(${@:2})
# run the process, stop, and save the PID
${command[@]} &
pid=$!
cg_name="${command[1]}.$pid"
kill -STOP $pid
# setup cleanup exit handler
cleanup() { kill -KILL $pid; sudo cgdelete -g "memory:$cg_name"; return 1; }
trap cleanup EXIT
# create the cgroup
sudo cgcreate -g "memory:$cg_name" || return 1
# setup memory limit
sudo cgset -r "memory.max=$size" "$cg_name"
echo "DEBUG: created cgroup $cg_name with max memory of $size"
# move the process to the cgroup
sudo cgclassify -g "memory:$cg_name" --cancel-sticky $pid
# restart the process and wait
kill -CONT $pid
fg
return $?
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment