Lately I have been writing a Java program that needs to run in the back ground (like a daemon). I found a couple of neat little tricks that can make this easier. These ideas probably only work in a Unix environment but they have been tested on Linux and Solaris.
So you have your program and you want to start it such that it will not be killed when you log out of the shell in which you start it. You could use nohup, but nohup redirects the standard out and error to files, which is annoying because you are writing all output to a log file anyway. You could do java -cp your_class_path com.domain.main_class <&- 1>/dev/null 2>&1 & which runs the program in the background, closes standard in, and redirects standard out and error to the bit bucket. By closing standard in to the process the shell will not kill the program when it exits and it is running in the background so it will not interfere with other actions we might want to perform with this shell.
However, it would be nice if you could print errors that occur during startup to the prompt — for example if the config file were missing. This is nice because it is generally appropriate to sanity check the configuration so that if the program starts there is a significant chance it will actually work correctly. So let’s not redirect standard out and error. That leaves you with java -cp your_class_path com.domain.main_class <&- &, which works but a shell will not exit while there are still programs attached to its standard out and error — as this one is.
The solution is to have the Java program detach from standard out and error once its startup is complete. So we will create a method called daemonize() that we will call just before entering the infinite loop that is the main program logic.
static public void daemonize()
{
System.out.close();
System.err.close();
}
This will allow any thing written to the console during startup to be seen by the user and it will allow the shell which starts the program to exit once the daemon’s startup has completed.
So now we have a main method which looks like
static public void main(String[] args)
{
try
{
// do sanity checks and startup actions
daemonize();
}
catch (Throwable e)
{
System.err.println("Startup failed.");
e.printStackTrace();
}
// do infinite loop
}
Now when we start our program we get to see if it started correctly and if it does start it will not be killed when the shell exits nor will it prevent the shell from exiting.
Now that the program is completely detached from the shell the only way to stop it is by killing the process. However, to do that you need to know the pid. Java has no way for a program to figure its pid directly — it is too system dependent. So we will create a shell script to launch our daemon and record its pid for future use.
#!/bin/sh
java -cp your_class_path com.domain.main_class <&- &
pid=$!
echo ${pid} > mydaemon.pid
This script launches the program and then writes the pid to the file ‘mydaemon.pid’. Now when you want to kill the program you can do kill `cat mydaemon.pid` There are a couple of problems with this, one is that the pid file gets written even if the daemon failed to start successfully, another is that if the daemon crashes the pid file will still exist — which might lead you to believe it is still working.
We can solve the pid file surviving daemon crash problem by passing it into the Java program like the following java -Ddaemon.pidfile=mydaemon.pid -cp your_class_path com.domain.main_class <&- & And the updated the daemonize() method to the following
static public void daemonize()
{
getPidFile().deleteOnExit();
System.out.close();
System.err.close();
}
where getPidFile() is a method which returns a File object file specified by the system property “daemon.pidfile”. That way the pid file will be deleted when the VM exits.
For the overly eager creation of the pid file you could add a delay to the shell script and then check to make sure the process is still running before writing the pid file. But how long should the delay be? A better way is to take advantage of the fact the a shell will not exit while a program is attached to its standard out or error — even if the process is running in the background. We know that our program will not detach from those until the startup process is complete. The following shell script achieves this
#!/bin/sh
launch_daemon()
{
/bin/sh <<EOF
java -Ddaemon.pidfile=mydaemon.pid -cp your_class_path com.domain.main_class <&- &
pid=\$!
echo \${pid}
EOF
}
daemon_pid=`launch_daemon`
if ps -p "${daemon_pid}" >/dev/null 2>&1
then
# daemon is running.
echo ${daemon_pid} > mydaemon.pid
else
echo "Daemon did not start."
fi
This script starts a sub-shell and launches the daemon (in the launch_daemon() function). The sub-shell will only return once the java program has detached from the console — for our program that means it has completed its startup or died. After the launch_daemon() function returns we check to see if the pid it started is still running. If so it means that the daemon started correctly and the we write the daemon’s pid to the pid file. Remember that whenever the daemon’s VM shuts down the pid file will be deleted so you can treat the existence of the pid file as an indication that the process is running.
Now it occurs to you that if a problem occurs during startup you really would like to log it to both the log file and console. Since you are using log4j this is pretty straight forward. Just updated you main method like the following
static public void main(String[] args)
{
Appender startupAppender = new ConsoleAppender(new SimpleLayout(), "System.err");
try
{
logger.addAppender(startupAppender);
// do sanity checks and startup actions
daemonize();
}
catch (Throwable e)
{
logger.fatal("Startup failed.",e);
}
finally
{
logger.removeAppender(startupAppender);
}
// do infinite loop
}
where “logger” is a static member variable that contains a Logger object. The nice thing about this is you can log message anywhere in you startup code and know that someone will see them, even if it occurs before you have configured the logging based on the application configuration. If the normal application logging is configured, the messages will go both to the console and to the log file for future debugging.
So all that works pretty well. There is another problem though. There is not a clean way to shut this daemon down. We need a graceful way to handle shutdown. So we add the following code to our main class
static protected boolean shutdownRequested = false;
static public void shutdown()
{
shutdownRequested = true;
}
static public isShutdownRequested()
{
return shutdownRequested;
}
Then we update our application so that occasionally it checks ‘isShutdownRequested()’ and if it is we leave the main loop. Now our main method looks like
static public void main(String[] args)
{
Appender startupAppender = new ConsoleAppender(new SimpleLayout());
try
{
logger.addAppender(startupAppender);
// do sanity checks and startup actions
daemonize();
}
catch (Throwable e)
{
logger.fatal("Startup failed.",e);
}
finally
{
logger.removeAppender(startupAppender);
}
while(!isShutdownRequested())
{
// wait for stimuli
// process stimulus
}
}
This looks pretty good but you still only shutdown from inside the program. The solution is a VM shutdown hook. The is a bit of code that the VM runs when it is shutdown. We create the following method
static protected void addDaemonShutdownHook()
{
Runtime.getRuntime().addShutdownHook( new Thread() { public void run() { MainClass.shutdown(); }});
}
and update the shutdown method as follows
static public void shutdown()
{
shutdownRequested = true;
try
{
getMainDaemonThread().join();
}
catch(InterruptedException e)
{
logger.error("Interrupted which waiting on main daemon thread to complete.");
}
}
Note that we now wait for the main daemon thread to die. This is because the VM waits for the VM shutdown hooks to complete for exiting but it does not wait for other threads to complete. This join allows the main daemon threads to complete in a controlled way rather than being killed by the VM. Then we update the main method to call this new addDaemonShutdownHook() method
static public void main(String[] args)
{
Appender startupAppender = new ConsoleAppender(new SimpleLayout());
try
{
logger.addAppender(startupAppender);
// do sanity checks and startup actions
daemonize();
addDaemonShutdownHook();
}
catch (Throwable e)
{
logger.fatal("Startup failed.",e);
}
finally
{
logger.removeAppender(startupAppender);
}
while(!isShutdownRequested())
{
// wait for stimuli
// process stimulus
}
// do shutdown actions
}
Now you can kill the process using kill `cat mydaemon.pid` but shutdown will be orderly and controlled.
So there you have it. A fairly safe and full featured way of create a Unix daemon with Java. Of course, if you do not need the extra control and do not mind have native binaries it might be easier to use Jakarta Daemon.
{Update: corrected a variable name in one of the shell scripts and added a needed closing brace to one of the bits of Java code}
Comments 44
great article, now heres a question for you, how do you keep it running after logout? I add nohup, and then have to redirect the output, any ideas?
Posted 21 Dec 2005 at 1:02 pm ¶The above code will continue running when you log out. The combination of closing the input stream on execution (the “
Posted 21 Dec 2005 at 5:09 pm ¶so by doing System.out.close and system.error.close, you essentially are disconnecting from the login anyways… because its no longer connected to an out?
Posted 22 Dec 2005 at 8:55 am ¶i answered my own question that does work.. pretty sweet.
Posted 22 Dec 2005 at 1:01 pm ¶Stupid html santization broke my last comment, sorry. :)
You have the right idea. By closing System.in, System.out and System.err the process is effectively disconnected from the terminal. The only real effect of this technique from the programs perspective is that System.out is close so that it cannot be written to. But generally we write stuff to the logs anyway. :)
Posted 22 Dec 2005 at 1:02 pm ¶BTW, note that System.in is closed when the java process is started by the “&<-” addition to the command line.
Posted 22 Dec 2005 at 1:04 pm ¶thanks… peter your blog entry helped me alot in getting this app transitioned to a unix service. I would like to contribute to your list of things to hate about java,
-there is too much documentation and not enough of it to the point
I had to take a windows service written in C# on windows and port it to run on unix, the port went ok, but finding realistic documentation on then deploying it as a unix daemon was few and far between. usenet groups a documentation does not make.
Posted 28 Dec 2005 at 12:39 pm ¶Glad I could help. I also find it odd that there is so little support for using Java as daemon/service. Especially since that seems to be the primary use for Java these days.
Posted 28 Dec 2005 at 5:59 pm ¶When I ran your script, it just hung at the line “daemon_pid=
launch_daemon“. The only way I can make the script continue is to kill the java process. So my question is that how do I make the java process to tell the script that “it has completed its startup”?Thanks
Posted 07 Jun 2006 at 11:00 am ¶Phi,
The code you are looking for is:
System.out.close();
System.err.close();
That will detach the java process from shell and allow the shell script to continue. In the article it is found in the
Posted 08 Jun 2006 at 9:25 am ¶daemonize()method.I’m a bit confused. You use the method: getMainDaemonThread(), however, I don’t see it declared anywhere. Maybe it’s in another blog entry that I’m missing, and if so, can you make a reference it? Thanks!
Posted 14 Jul 2006 at 7:56 pm ¶I also noticed the same thing with regards to your “daemonize()” method. Can you clarify?
Posted 14 Jul 2006 at 8:13 pm ¶Scratch the daemonize comment.. I wasn’t being very observant.
Posted 14 Jul 2006 at 8:14 pm ¶Ryan,
I did fail show the tracking of the thread. For this to work, you need to store the current thread during the deamonize() method in a member variable and getMainDaemonThread() returns that thread.
Posted 16 Jul 2006 at 10:32 pm ¶Ok. So for those who come after me, this is what I added and it seems to work just fine (if this comes out unformatted, my apologies):
Posted 17 Jul 2006 at 4:16 pm ¶Hi, I think your java solution daemon is great. I will build on it. Anyway, I would have a specific additional need: I would like that the daemon be able to receive commands (from the command line) like restart, trace, etc. Your solution does provide the required persistancy. I suppose that the “System.in.close()” line, wich kills terminal dependancy, makes impossible input command solution.Am I correct? Thanks in advance for your help. Regards, François.
Posted 01 Aug 2006 at 6:54 am ¶The closing ‘System.in’ does make sending commands more difficult.
However, I can imagine several ways to send commands to a daemonized
process.
a Posix compatibility library for Java would allow you to use
standard Unix signals like HUP, TERM and USR1 using the kill
command the
daemonized process could open socket (probably a Unix domain
socket) when it was start and listen for commands sent on that socket
files with commands in them could be created in a temporary
directory and the daemonized process could poll the directory for
new commands
All of these approaches would work. To my taste the second one seems
Posted 07 Aug 2006 at 8:23 am ¶the most elegant because it does not require an native library like
the first one and does not require directory polling like the last
one. However the second choice is probably the most work.
How can be done in windows?
Not with all the functionality you presented, just the main stuff.
Thanks in advance.
Posted 11 Aug 2006 at 8:48 am ¶I really don’t know. You might take a look at this or something like FireDaemon. I have no knowledge of either but they might work for you.
Posted 11 Aug 2006 at 10:02 pm ¶Pete,
I have trouble getting the rest of the code for the method addDaemonShutdownHook. The wepage got cut off for some reason. Can you send me the rest ?
Posted 31 Aug 2006 at 10:04 pm ¶Hi,
I tried verifying that:
“The sub-shell will only return once the java program has detached from the console”
With the following shell snippet:
!/bin/sh
set -e
start() {
/bin/sh <!/usr/bin/env python
from time import sleep
print “daemon start”
sleep(5)
print “daemon end”
Calling the shell snippet results in:
bee% ./foo.sh
pid=7400
returned
bee% daemon start
daemon end
Note how I immediately get a prompt back and how “returned” is printed way before daemon end. It doesn’t seem to me that the foo.sh /bin/sh is waiting for the inlined /bin/sh sub-shell to return.
However, I could verify that the my-daemon process outlives the shell, even if I close the terminal (xterm) from which I am doing the tests.
Bye,
Posted 13 Dec 2006 at 5:27 am ¶Hi!
Great article …if I only could get it to work ;)
I’ve been messing around with the shell script, but all I get is “Daemon did not start.”.
Seems like the daemon_pid string contains the pid twice. The following code:
prints the following:
3453 3453
Daemon did not start.
..if the PID was 3453. In other words it seems like the if-statement won’t give a match.
Can anyone spot the problem?
I run this under Fedora Core 6.
Best regards!:)
Posted 13 Dec 2006 at 1:59 pm ¶Howard,
The only thing I can think of is that you might have added some debug printing to the
launch_daemonfunction? Any additional calls toechoin that function will break it.If the above is not the problem I would added some delimitation around the echo to make sure that the value of daemon_pid is really broken and it is not just getting printed twice. For example,
Posted 27 Dec 2006 at 9:52 am ¶Thank you for this information. It has proved very usefull.
Posted 12 Mar 2007 at 10:26 am ¶How to run a shell script from a java program in new terminal window,not in my programs’ console. since my shell script will hold the step by step process to start my uml in terminal. plz give ur idea n this?
Thanks in advance…
Posted 29 Mar 2007 at 7:06 pm ¶A wonderful artical. Thanks Peter! Here are three comments:
Comment #1
If you want to add debug to launch_daemon you can do this:
echo “my debug output” 1>&2
1>&2 redirects stdout to stderr and will not intefere with the correct capture of the pid by the invoking shell script.
Comment #2
I had a similar expereience to Loïc Minier. I don’t know python so I did not try to analyze his script but I believe I have finally figured out what is going on. I think your statement “The sub-shell will only return once the java program has detached from the console — for our program that means it has completed its startup or died.” is inaccurate. launch_daemon does NOT block waiting for stdout/stderr of the daemon to close. It’s the fact that you execute launch_daemon in back-tics that is causing execution to block until stdout is closed.
I think that when you invoke a shell function or program in back-tics the stdout from that program is redirected to the outter shell script (so it can be processed as part of that outter shell script in-line). It makes sense to me that shell back-tic processing would wait for the stdout of that subshell to close before passing the results back to the outter shell. If you don’t use back-tics, then the stdout of the subshell is tied to the stdout of the outter shell and nothing is waiting for that stream to close, so everything just keeps going. Mind you, I really don’t know what I’m talking about — my explanations are just theories. :)
Comment #3
I’ve written some reusable shell functions that allow you to invoke the java program directly from an init.d script. I won’t post them all here, but perhaps some may find my variation on launch_daemon useful in that it allows you to kick the thing off as a different user:
launch_daemon()
{
daemonUid=$1
daemonCommandLine=$2
EOF”
}
Which you can invoke like so:
daemonpid=
launch_daemon someuser "java com.mycompany.MyDaemon"Thanks again!
Posted 26 Apr 2007 at 11:07 am ¶Matt Busche
Ugh. After all that talk of back-tics, I left them off in that example in comment 3. Should be:
daemonpid=
launch_daemon someuser "java com.mycompany.MyDaemon"Matt Busche
Posted 27 Apr 2007 at 2:53 pm ¶I really like your write-up on Daemons, at least i now have a nrw insight into what it is all about. Thanks
Posted 01 Jun 2007 at 1:39 pm ¶Thanks for this very informative article on daemons.
Posted 25 Jun 2007 at 1:37 am ¶Hi There,
Thanks for the great information. I am just wondering how to prevent the service from consuming loads of CPU time when it is just listening. I have quite a few internal threads, will calling Thread.yield() in all of my run loops lower the idle cpu usage?
Posted 10 Jul 2007 at 7:02 pm ¶Guy,
If I recall my Java threading model correctly, calling
Posted 11 Jul 2007 at 9:15 am ¶Thread.yieldwill have no effect unless you are using green threads (and even then
it will probably not have any noticeable effect) . You need to add
some sort of blocking read to your loops so that they just wait until
there is new data or a new connection to handle. Alternatively, you
could add a sleep to the processing loop but that would be a distance
second choice as far I am concerned.
This blog post is completely awesome. I haven’t seen this documented in any book or anywhere else on the Internet.
It surprises me to learn that there really isn’t anything “special” about a Linux daemon process.
I am happy to report that the above code works great with /etc/init.d/ and /sbin/service
Posted 20 Aug 2007 at 4:24 pm ¶Linux seems to return more than one pid.
Try daemon_pid=
Posted 31 Aug 2007 at 8:28 am ¶launch_daemon | head -1I tried to above
daemon_pid=launch_daemon | head -1
but it didn’t quite work for me (fedora 7)… I found that having the pipe to head in there caused the backquotes to return “early” before err/out were closed, defeating the whole purpose of the mechanism…
I got it to work by putting the “head” in its own separate step:
daemon_pid=
launch_daemondaemon_pid=
echo ${daemon_pid} | head -1(NOTE- backquotes are probably missing in this blog post comment (stripped out by the blog software) but they most certainly need to be in there just like in the original post)
Great post! Thanks!!!
Posted 11 Nov 2007 at 12:39 pm ¶모니이게?
Posted 29 Jan 2008 at 11:12 pm ¶I made some modifications to the original skeleton to replace the shell script by a Perl script. The Perl script is forking the child process and launching the Java daemon, the Java daemon open a named pipe created by the Perl script for writing and the parent process is opening the named pipe for reading. While initialization of the Java daemon is done, a message is sent in the named pipe and the Perl parent program resume execution creating the pid file. I also added the verification for the pid file prior starting the Java daemon in the Java daemon as part of initialization to avoid starting two instances of the same daemon.
I am locking the PID file in the Perl script, but this is not really necessary, remanent code from testing an approach with file locks.
Here is the Perl script:
!/usr/bin/perl
#
#
use Env;
use Fcntl ‘:flock’;
use File::Basename;
use Shell qw(mkfifo);
$pidfile=’/var/tmp/’ . (split(/./,basename($0)))[0] . ‘.pid’;
$fifoname = ‘/var/tmp/.’ . (split(/./,basename($0)))[0] . ‘.fifo’;
$classpath=$ENV{CLASSPATH} . ‘:yourclasspath’;
$ENV{CLASSPATH} = $classpath;
unlink($fifoname);
sub start_daemon() {
push(@javadaemoncmd,”java”);
push(@javadaemoncmd,”-Ddaemon.pidfile=” . $pidfile); push(@javadaemoncmd,”com.acme.coyote.testing.RRCatcherDaemon”);
push(@javadaemoncmd,$fifoname);
push(@javadaemoncmd,”<&-”);
push(@javadaemoncmd,”&”);
}
my $rc = 0;
my ($dpid,$message) = start_daemon();
unlink($fifoname);
if ( $dpid ) {
kill(0,$dpid);
my $code = $?;
if ( $code eq 0 ) {
if ( open(PIDFILE,”>>$pidfile”) ) {
flock(PIDFILE,LOCK_EX);
print PIDFILE $dpid;
flock(PIDFILE,LOCK_UN);
close(PIDFILE);
} else {
$rc = 1;
print “Cannot open pid file \”" . $pidfile . “\”.n”;
}
} else {
print “Process: “, $dpid, ” no longer present.n”;
print $message, “n”;
}
} else {
$rc = 2;
print $message, “n”;
}
exit($rc);
I wrote three methods: openFifo(), closeFifo() and sendFifo() which I use in the Java daemon initialization phase. As soon as the named pipe (FIFO) is opened, the System.err and System.out can be closed since all messages between the Perl parent script and the Java daemon will pass through the named pipe.
Posted 10 Mar 2008 at 5:03 pm ¶Thanks for the excellent tutorial Peter. I was able to create a java-based daemon modeled after your approach and saved hours (probably days?) of time. Great job!
Posted 02 May 2008 at 9:18 am ¶I have a requirement to write a java daemon in Unix, which will be an java application. For example say abc.java. which should print “hello world” whenever i call the application. I have few questions is -
How to make a call to a daemon ?
Do i have to extend Thread in my abc.java class to runn continuesly in the background?
Thanks
Posted 02 May 2008 at 1:13 pm ¶Hi Peter,
I daemonized my java application using your method, and everything looked great until QA run it over SSH. Turns out it causes the SSH to hang on exit. SSH also kills the app if the output is redirected on the command line :-(
I am using Redhat.
Any ideas?
Thanks,
Posted 27 May 2008 at 3:23 pm ¶Arkadiy
Arkadiy Vertleyb,
That is weird. I developed this approach to daemonization precisely to avoid the hanging/killing that normally takes place when you launch an app over ssh. To be perfectly honest I have any contact with a system using this approach in several years so debugging your problem could be difficult for me. :)
Posted 27 May 2008 at 5:51 pm ¶I am having trouble getting this to work under Solaris 10. I’m using the CDE and open a terminal window to start my app. I switch to root and just execute the command line:
java -cp your_class_path com.domain.main_class <&- 1>/dev/null 2>&1
(I’m just trying to get the program to continue to run atm).
The program executes normally, however when I close the terminal window (via exit, exit) my application goes away.
Any clues as to what I might be doing wrong? I even added the Daemonize routine to close stdin, stderr and stdout, but it still stops when the terminal window is closed.
Posted 29 May 2008 at 7:53 am ¶Thanks for this article, it’s exactly what I needed to know in order to continue with my project.
Posted 30 May 2008 at 5:17 am ¶Thanks for this post, found it in the nick of time!
Posted 18 Jun 2008 at 5:24 am ¶Thanks for the post Peter. Very useful stuff!
Posted 23 Jun 2008 at 12:00 pm ¶Trackbacks & Pingbacks 2
[…] Peter Williams » Java Daemon saved me a few hours… (tags: Java) […]
[…] Using a daemon thread with ShutdownHook For example, JBoss uses shutdownHook.setDaemon(true) or do this (Java Daemon). […]
Post a Comment