문제

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),
  • and the process list will then be filtered first to exclude any instances of grep
  • and second to count the processes specified with $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.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top