title: Simpler init script for Java daemons?
body: <p>I've written a small library for creating services/daemons in Java. The idea is simple. When you start your application you pass a command and a port number. If the command is a start command, a new instance of your application will be started on the specified port. Otherwise, the command will be sent to any instance that might be running on that port.</p>
  
  <p>In short, the library provides a daemonize method that starts a daemon controller thread. It uses sockets to make your application communicate with instances of itself (as you've probably already figured out).</p>
  
  <p>For clarity, here's an example of how you would use it:</p>
  
  <pre><code>public class MyApp extends Daemon
  {
      public static void main(String[] args)
      {
          if (daemonize(MyApp.class, args))
          {
              // normal main body
              startMyServerOrWhatever();
          }
          else
          {
              // failed to start or send command to daemon
              // probably wrong syntax or unknown command
              printUsageInfoAndExit();
          }
      }
  
      @Command(start = true)
      public static int start()
      {
          // executed on "start" command, e.g. java -jar MyApp.jar start 8899
          doSomeInitializing();
          return 0; // return 0 or void to detach from console
      }
  
      @Command
      public static void mycmd()
      {
          // executed on "mycmd" command, i.e. java -jar MyApp.jar mycmd 8899
          doSomethingCool();
      }
  
      @Command(stop = true)
      public static int stop()
      {
          // executed on "stop" command, i.e. java -jar MyApp.jar stop 8899
          doSomeCleanup();
          return 0; // used as application exit code
      }
  }
  </code></pre>
  
  <p>The library works really well and I've used it to create a couple of daemons that will run on a Linux server. What's missing now is some scripts to let the admins control these daemons like they control other daemons on the server (e.g. start at boot).</p>
  
  <p>Unfortunately my *nix skills, especially when it comes to scripting, are not top level. I have a basic understanding of the BSD-style init procedure (rc.d), but looking at sample scripts like <a href="http://www.source-code.biz/snippets/java/javaDaemonTest.sh.txt" rel="nofollow">this one</a> I feel a little lost.</p>
  
  <p>So my question is, <strong>isn't there a simpler way to do this</strong> in my case? I mean, my daemons already understand the commands and should themselves be responsible for any actions (except in the case where a daemon doesn't respond to stop - it should then be killed after some timeout).</p>