1

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?

pythonic metaphor
  • 10,296
  • 18
  • 68
  • 110
  • I'd recommend against using recursion to create new processes, period. Use an iterative construct instead. – chepner Feb 03 '14 at 15:39

2 Answers2

5

You could use ulimit

ulimit -u 20

Will limit the maximum number of processes runned by your user

Raul Andres
  • 3,766
  • 15
  • 24
  • Doesnt this limit the number of all processes instead of only the processes of the particular script? – eckes Feb 03 '14 at 16:59
  • 1
    @eckes Yes, but the OP is requesting for a sandbox to recover from fork bombs while debuging, so using a dedicated user or temporary limit the shell with ulimit does the trick. – Raul Andres Feb 03 '14 at 17:17
2

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.
eckes
  • 64,417
  • 29
  • 168
  • 201
  • 1
    @l0b0: http://askubuntu.com/questions/157075/why-does-ps-aux-grep-x-give-better-results-than-pgrep-x – eckes Feb 03 '14 at 15:55