views:

103

answers:

4

I need to run an java program even the terminal is closed.... in server....

A: 

You want to use headless mode. This will cause any calls that attempt to communicate with a screen, keyboard, mouse, etc to fail, but also means that you won't need an X server (on Unix) or access to the console (on Windows).

Craig Trader
This is only relevant when you're using GUI-related classes, which most server applications never do.
Michael Borgwardt
It's very relevant for working with images on a server, since all of the image processing classes depend upon the AWT. Using headless will give you a simpler version of the AWT that doesn't require a window.
Craig Trader
+1  A: 

Use the javaw command instead of java.

Michael B.
It will still get shut down when the user logs out.
Michael Borgwardt
@Michael, Well the question is not clear, I thought he mean that the console should not run while the app is running.
Michael B.
+2  A: 

On Unix and GNU/Linux systems you can run the program using nohup like this, assuming it is a jar:

nohup java -jar program.jar &

To get the output of the program run into a text file so later on you can view it, you can do:

nohup java -jar program.jar > program.log &

There are packages that will wrap your Java programs into services too, which is more manageable than bare java processes.

You probably also want to use a "process wrapper" (Launch4J maybe?) to give your process a meaningful name, otherwise all your Java programs will appear as java in the process list, which isn't very indicative.

Bakkal
A: 

An "alternative" to nohup would be screen. screen is very useful and allows you to run any task, detach the screen, and let it run in the background. You can resume it later.

To run a task:

screen <command_you_want_to_run>

Then <ctrl> <a> <d> to detach from the screen session.

The next time you log in you can reattach to the screen session with:

screen -r

If you have multiple screen sessions running you will be presented with their details and can connect to them like this:

screen -r 1234.pts-1.hostname

... where 1234.pts-1.hostname is one of the returned values from the output from screen -r.

Pascal Thivent