title: Linux Single Instance Kill if running too long
body: <p>I am using the following to keep a single instance of a script running on my server. I have a cronjob to run this every minute.</p>
  
  <p><a href="https://stackoverflow.com/questions/525247/how-do-i-daemonize-an-arbitrary-script-in-unix">How do I daemonize an arbitrary script in unix?</a></p>
  
  <pre><code>#!/bin/bash
  
  if [[ $# &lt; 1 ]]; then
      echo "Name of pid file not given."
      exit
  fi
  
  # Get the pid file's name.
  PIDFILE=$1
  shift
  
  if [[ $# &lt; 1 ]]; then
      echo "No command given."
      exit
  fi
  
  echo "Checking pid in file $PIDFILE."
  
  #Check to see if process running.
  PID=$(cat $PIDFILE 2&gt;/dev/null)
  if [[ $? = 0 ]]; then
      ps -p $PID &gt;/dev/null 2&gt;&amp;1
      if [[ $? = 0 ]]; then
          echo "Command $1 already running."
          exit
      fi
  fi
  
  # Write our pid to file.
  echo $$ &gt;$PIDFILE
  
  # Get command.
  COMMAND=$1
  shift
  
  # Run command
  $COMMAND "$*"
  </code></pre>
  
  <p>Now I found out that my script had hung for some reason and therefore it was stuck. I'd like a way to check if the <code>$PIDFILE</code> is "old" and if so, kill the process. I know that's possible (check the timestamp on the file) but I don't know the syntax or if this is even a good idea. Also, when this script is running, the CPU should be pretty heavily used. If it hangs (rare but it happened at least once so far), the CPU usage drops to 0%. It would be nice if I could check that the process is really hung/not active, but I don't know if there's an easy way to do that (and I don't want to have many false positives where it gets killed but it's running fine).</p>