This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.
Last Updated: 2024-11-21
For a laugh I wanted to overload my system from bash. I found the following snippet online:
function malloc() {
if [[ $# -eq 0 || $1 -eq '-h' || $1 -lt 0 ]] ; then
echo -e "usage: malloc N\n\nAllocate N mb, wait, then release it."
else
N=$(free -m | grep Mem: | awk '{print int($2/10)}')
if [[ $N -gt $1 ]] ;then
N=$1
fi
sh -c "MEMBLOB=\$(dd if=/dev/urandom bs=1MB count=$N) ; sleep 1"
fi
}
How does this work?
The first two lines of the function look at the arguments given. Help is echoed to the user if:
-h
(for help) is givenThe rest of the code involves the use of the free
command as well as the dd
command.
free
exists only in unix (not on macos). It displays the amount of free and
used memory in a system.
dd
is often used for reading data from a device
if
specifies which "file" is the input. Here it is /dev/urandom
noise
bs
is how many bytes are read at a time
count
is how many input blocks
Together this reads 1mb times the function input ($1
) worth of noise and assigns
it to a constant MEMBLOB
in a subshell that lasts 1 second, then relinquishes
it. But before the memory is relinquished, the RAM usage increases.