recipe № 022

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

Let’s say you want to run a daemon. And, for some reasons, you want to launch it using Java. For example, you have lots of preinitialization steps already written and code itself is Java based). In that case, execution schema will look like picture below

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

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.

Note that we will never get back to Java here. You can find another sample, where service part of daemon is executed in Java, here: recipe № 029. Full sample code for recipe recipe № 022 can be found at following location: recipe № 022 – sample code.


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