How to run a java program in backgroud (unix / Linux)

Oftentimes, we use SSH to remote access into the server to run a Java program. The problem is, we can’t type anything After the Java program is executed like this :


$ java -jar example.jar

In addition, when the remote access session is expired or terminated, the executed Java program will be killed.

Solution

To fix it, append a & symbol to the end of the command, it executes the Java program in the background, and continue until it finished.


$ java -jar example.jar &

If the above command get killed when you leave the SSH session, try to add nohup in front.


$ nohup java -jar example.jar &
author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
3000
newest oldest most voted
Vikas
Guest
Vikas

Thanks a ton !!!…Really helpful

Rakh
Guest
Rakh

I know this was posted long ago, sorry about commenting on it.
I’ve got an issue related to this, driving me crazy. When I run my jar on linux prompt with a command like this:
java -jar MyJar.jar &
the process starts running in background as expected, but this process always gets killed some time later, say 2 hours for a reason I can’t figure out; Not memory issues because I’ve tried VM option (Xmx) and never getting the exception. Also no logs found in kernel about it.
But if I start app without the & sign and keep the console open, it will continue running as long as I have the console opened.
Does this mean anything to you? Any suggestion please.

mkyong
Guest
mkyong

Try nohup

nohup java -jar example.jar &

snrat
Guest
snrat

It still does not work for me.
pid gets created and it runs once .then when i do ps-fp ,it does not give any process

arche
Guest
arche

Even though the post is old. Maybe you run it as a different user and then you exit, or if not, you need to do the following nohup java -jar MyJar.jar &

Lindsay
Guest
Lindsay

Very nice mkyong. It worked for me.

Freakygeek
Guest
Freakygeek

If i close my SSH like Putty, will it stop the process?

Cesarla
Guest
Cesarla

Really useful, you save my life!

cracker
Guest
cracker

any body tell me how to do it in windows xp……….

mkyong
Guest
mkyong

On Windows, try task scheduler

suhana
Guest
suhana

>javac filename.java
>java filename

Linh Locklier
Guest
Linh Locklier

I think I will give this a try, thanks for the post.

Mangara
Guest
Mangara

Thanks! Exactly what I was looking for.

jeff
Guest
jeff

tnx.. i found 1 of my assignments…
can you help me some times if i have my other assignments?…

software development company
Guest
software development company

Interesting,

Although linux is not so widely used ,

Keep up the good work