0

In java, I need to make a unix daemon. So I need to create the sockets and then fork, so that systemd knows that the service is actually ready.

In C, this is normally done like this:

int main() {
    initialise_socket();
    daemon(0,0);
}

So that when the process terminates, systemd (or upstart, or sysvinit) know that the daemon is ready to accept connections, and daemons that depend on it can now be started.

My question is: how can I do this in java?

I have googled around and found a lot of misguided advice about starting java using nohup, which in no way does what I need to do.

LtWorf
  • 7,286
  • 6
  • 31
  • 45
  • 1
    Possible duplicate of [How to Daemonize a Java Program?](https://stackoverflow.com/questions/534648/how-to-daemonize-a-java-program) – Adam Michalik Jul 21 '17 at 09:33
  • @AdamMichalik It has nothing to do with that question. That's about detaching from a shell, and I already mentioned it's not relevant to what I need. – LtWorf Jul 21 '17 at 10:40
  • It seems like someone removed my answer ;) Anyway, for the record. You can find solution here: http://jnicookbook.owsiak.org/recipe-No-022/ and here http://jnicookbook.owsiak.org/recipe-no-029/ – Oo.oO Jul 23 '17 at 15:22
  • @LtWorf you might need to describe in more detail what you need and in what ways the other answers were not helpful. – Adam Michalik Jul 24 '17 at 08:17
  • @AdamMichalik I want to do the same as that C code does, but in Java. – LtWorf Aug 17 '17 at 13:42

2 Answers2

1

Pure Java application (without using JNI=native C code) cannot daemonize itself - there are no methods for that in the JDK. What you can do is run the java process (the VM that runs your application) using a deamonizing utility, like start-stop-daemon

Adam Michalik
  • 9,678
  • 13
  • 71
  • 102
-1

I have used the Apache module commons daemon to implement a daemon on Unix.

https://wiki.apache.org/commons/Daemon

It is not as flexible as writing a daemon in C, but in the end it was sufficient.

The usage is quite simple. You just have to implement a start and stop method.

ceving
  • 21,900
  • 13
  • 104
  • 178