You could use ulimit
ulimit -u 20
Will limit the maximum number of processes runned by your user
문제
I was experimenting with a bash script that would recursively fork and call itself. The terminating condition was subtle and I got it a wrong a few times, the result being a script that called itself ad infinitum. What's a safe way to sandbox a script like this while debugging it so that every time there's a mistake, I don't have to deal with stopping the infinite tower that fills up the process table?
해결책
You could use ulimit
ulimit -u 20
Will limit the maximum number of processes runned by your user
다른 팁
You could simply count the numbers of processes with your script name and terminate if the number gets too high.
This blog post introduces a function to achieve this:
count_process(){
return $(ps -ef | grep -v grep | grep -c $1)
}
Explanation (taken from blog post):
ps -ef
will return a list of all running processes (in detail),grep
$1
For re-usability the author provides the function as little script:
#!/bin/sh
#
# /usr/bin/processCount
# Source: http://samcaldwell.net/index.php/technical-articles/3-how-to-articles/68-how-do-i-count-the-number-of-linux-instances-of-a-given-process-using-a-bash-script
#
[ -z $1 ] && {
echo " "
echo "Missing expected input."
echo " "
echo "USAGE:"
echo " "
echo " $0 <executable file>"
echo " "
echo " NOTE: When executing this script use the path and filename of the"
echo " program. Using only the process name can potentially return inaccurate"
echo " results."
echo " "
exit 1
}
echo $(ps -ef | grep -v grep | grep -v $0 | grep -c $1)
#script ends here.