title: How do I daemonize an arbitrary script in unix?
body: <p>I'd like a daemonizer that can turn an arbitrary, generic script or command into a <a href="http://en.wikipedia.org/wiki/Daemon_(computer_software)" rel="noreferrer">daemon</a>.</p>
  
  <p>There are two common cases I'd like to deal with:</p>
  
  <ol>
  <li><p>I have a script that should run forever.  If it ever dies (or on reboot), restart it.  Don't let there ever be two copies running at once (detect if a copy is already running and don't launch it in that case).</p></li>
  <li><p>I have a simple script or command line command that I'd like to keep executing repeatedly forever (with a short pause between runs).  Again, don't allow two copies of the script to ever be running at once.</p></li>
  </ol>
  
  <p>Of course it's trivial to write a "while(true)" loop around the script in case 2 and then apply a solution for case 1, but a more general solution will just solve case 2 directly since that applies to the script in case 1 as well (you may just want a shorter or no pause if the script is not intended to ever die (of course if the script really <em>does</em> never die then the pause doesn't actually matter)).</p>
  
  <p>Note that the solution should not involve, say, adding file-locking code or PID recording to the existing scripts.</p>
  
  <p>More specifically, I'd like a program "daemonize" that I can run like</p>
  
  <pre><code>% daemonize myscript arg1 arg2
  </code></pre>
  
  <p>or, for example, </p>
  
  <pre><code>% daemonize 'echo `date` &gt;&gt; /tmp/times.txt'
  </code></pre>
  
  <p>which would keep a growing list of dates appended to times.txt. (Note that if the argument(s) to daemonize is a script that runs forever as in case 1 above, then daemonize will still do the right thing, restarting it when necessary.)  I could then put a command like above in my .login and/or cron it hourly or minutely (depending on how worried I was about it dying unexpectedly).</p>
  
  <p>NB: The daemonize script will need to remember the command string it is daemonizing so that if the same command string is daemonized again it does not launch a second copy.</p>
  
  <p>Also, the solution should ideally work on both OS X and linux but solutions for one or the other are welcome.</p>
  
  <p>EDIT: It's fine if you have to invoke it with <code>sudo daemonize myscript myargs</code>.</p>
  
  <p>(If I'm thinking of this all wrong or there are quick-and-dirty partial solutions, I'd love to hear that too.)</p>
  
  <hr>
  
  <p>PS: In case it's useful, <a href="https://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python">here's</a> a similar question specific to python.</p>
  
  <p>And <a href="https://stackoverflow.com/questions/38596/whats-the-best-way-to-keep-a-php-script-running-as-a-daemon/39609#39609">this</a> answer to a similar question has what appears to be a useful idiom for a quick-and-dirty demonizing of an arbitrary script:</p>