recipe № 029

running Java as daemon – main daemon’s loop in Java

Let’s say you want to run a daemon. And, for some reasons, you want to launch it using Java. For example, you have some sort of code that is supposed to run as a service. What you can do here is to run daemon initialization using JNI and then, proceed in Java. More or less here is the schema.

What we need here, is C based daemon stub. Code that will “daemonize” Java process.

In addition to that, we need Java part that will be responsible for running “forever loop” where service code should be located.

Thanks to running code via JNI we can perform all daemon based setup:

      – setting custom SID for process,
      – changing dir to “/”,
      – closing standard streams: input, output, error – and attaching them to /dev/null,
      – executing endless loop.

In this sample, we are getting back to Java (in opposition to sample: recipe № 022). In here, service part is fully maintained by Java. Full sample code for recipe recipe № 029 can be found at following location: recipe № 029 – sample code.

References:

– Robert Love, Linux System ProgrammingDaemons
– Devin Watson, Linux Daemon Writing HOWTO