-
Notifications
You must be signed in to change notification settings - Fork 56
Bash sample code: Memory leak test script
Jean-Michel Gigault edited this page Dec 22, 2015
·
11 revisions
This is how to make a simple bash script that detects memory leak -- memory that the application has allocated, but has been lost and cannot be freed -- using any debugger tool that requires installation.
Requirement: The program from which you want to detect memory leak need to be running at least 15 consecutive seconds, enough time for it to generate memory leak (or not) and to let the bash script making its job at the same time.
function detect_memory_leaks
{
local PROG_PATH=$1 # 1st argument: The path to the executable to test
# run the executable silently and send it to background using '&'
($PROG_PATH >/dev/null 2>&1) &
# get its process ID with '$!' and save it in a variable PID
local PID=$!
# wait for 5 seconds to let the executable generating memory leak (or not)
sleep 5
# check if the process is still running in background
# if not, we cannot detect memory leak and we must stop the test
if [ -z "$(ps a | awk -v PID=$PID '$1 == PID {print}')" ]
then
echo "An error occurred: The program has terminated too quickly"
return
fi
# run the 'leaks' command with the process ID as argument,
# and save the outputted line where total leaked bytes appears
local RESULT=$(leaks $PID 2>/dev/null | grep 'total leaked bytes')
# note: the user may be asked for his administrator password
# that's why we need the executable to be running 15 seconds at least
# letting the user entering his password if necessary
# kill the executable, as we do not need it to be running anymore
kill -9 $PID >/dev/null 2>&1
# test if RESULT is empty
if [ -z "$RESULT" ]
then
# if yes, that means the command 'leaks' has failed
echo "An error occurred: Unable to detect memory leak"
else
# otherwise, display the total leaked bytes
echo $RESULT
fi
}
detect_memory_leaks "./ft_ls -R /Users"
(to be written)
(to be written)
(to be written)
Introduction:
- What is Bash
- What is a bash script
- What is 42FileChecker
- Contributing to 42FileChecker
Bash syntax:
Bash tools:
- Builtin commands
- Awk
- Cat
- Grep
- Sed
Bash sample codes:
- Script auto-update (git tool)
- Create an interactive menu
- Animated spinner with a time out
- Static var test
- Check the basic rules of a makefile
- Forbidden functions test
- Memory leak test script
- Create a speed test