title: How to start a Linux service (Bash script) containing an infinite loop in the start method
body: <p>I'm trying to check whether one of my process is running or not every 10 minutes and if not, restart that process. I want this script to start automatically when the system boots up, so I go for <a href="https://unix.stackexchange.com/questions/1924/create-services-in-linux-start-up-in-linux">services in Linux</a>.</p>
  
  <p>So here is what I did:</p>
  
  <ul>
  <li>Wrote a Bash script as a service.</li>
  <li>In the <code>start</code> method of the shell
  script, in an infinite while loop, check whether a temporary file exists.
  If available do my logic, else break the loop.</li>
  <li>In the <code>stop</code> method,
  delete the temporary file.</li>
  <li>Then I used update-rc.d to add this script to
  system boot up.</li>
  </ul>
  
  <p>Everything was working fine, except one thing. If I do <code>./myservice start</code>, then the terminal hangs up (it should as it's running an infinite loop), but if I do a <code>ctrl-z</code> then the script is killed and my task won't perform. How can I make this script to start from the terminal and execute normally? (like, say, <code>./etc/init.d/mysql start</code>). Maybe do the process in the background and return.</p>
  
  <p>My Bash script is given below:</p>
  
  <pre><code>#!/bin/bash
  
  # Start the service
  start() {
  
      #Process name that need to be monitored
      process_name="mysqld"
  
      #Restart command for process
      restart_process_command="service mysql start"
  
      #path to pgrep command
      PGREP="/usr/bin/pgrep"
  
      #Initially, on startup do create a testfile to indicate that the process
      #need to be monitored. If you dont want the process to be monitored, then
      #delete this file or stop this service
          touch /tmp/testfile
  
          while true;
          do
  
          if [ ! -f /tmp/testfile ]; then
               break
          fi
  
          $PGREP ${process_name}
  
          if [ $? -ne 0 ] # if &lt;process&gt; not running
          then
          # restart &lt;process&gt;
          $restart_process_command
          fi
  
          #Change the time for monitoring process here (in secs)
          sleep 1000
  
      done
  }
  
  stop() {
         echo "Stopping the service"
         rm -rf /tmp/testfile
  }
  ### main logic ###
  case "$1" in
    start)
          start
          ;;
    stop)
          stop
          ;;
    status)
          ;;
    restart|reload|condrestart)
          stop
          start
          ;;
    *)
          echo $"Usage: $0 {start|stop|restart|reload|status}"
          exit 1
  esac
  exit 0
  </code></pre>