How to safely experiment with scripts that fork themselves

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?

Answers


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.

Need Your Help

LISTAGG function: "result of string concatenation is too long"

sql oracle

I'm using Oracle SQL developer version 3.0.04. I attempted to use the function LISTAGG to group the data together..

Using a debugger and curses at the same time?

python exception interpreter curses pdb

I'm calling python -m pdb myapp.py, when an exception fires, and I'd normally be thrown back to the pdb interpreter to investigate the problem. However this exception is being thrown after I've cal...