Ubuntu – How to run a Java program in background

background-processbashjavascriptsssh

I try to make a init.d script which should start this java command:

java -cp ./:/opt/glassfish/domains/domain1/lib/*:/opt/glassfish/lib/* com.name.it.svcimpl.OrderRequestDispatcher &

With & it starts as background process and this is fine. The problems are starting when you are trying to get it to the foreground:

[1] 10119
user@server:$ fg 10119
-bash: fg: 10119: no such job

After you are pressing enter this happens:

[1]+  Stopped                 java -cp ./:/opt/glassfish/domains/domain1/lib/*:/opt/glassfish/lib/* name.alcar.it.svcimpl.OrderRequestDispatcher

As you see there was no process like 10119 so why does it stop?
But the things getting much more difficult when the command is in a init.d bash script:

#!/bin/bash
(cd /opt/glassfish/domains/domain1/applications/AS/WEB-INF/classes; java -cp ./:/opt/glassfish/domains/domain1/lib/*:/opt/glassfish/lib/* com.name.it.svcimpl.OrderRequestDispatcher &)

(Need to started under the path /opt/glassfish/domains/domain1/applications/AS/WEB-INF/classes)

Now my question as not java programmer is:

  • Is it possible to run a java program in background with the option to foreground it from any terminal session?

As you can read it is really important to run it in background. Any user that are logged in should be able to put it to the foreground. The users are connecting with SSH to the terminal.

Best Answer

You can't foreground a process from a different sesion. The functionality you want is probably possible with the screen command.

As for the java app failing to run in init.d; you are not changing to the /opt/glassfish/domains/domain1/applications/AS/WEB-INF/classes folder. You have '.' in your classpath so it matters where you run from.

Ideally, I think you should keep the bash script and run that from init.d. However, you could also add the full path to your init.d classpath explicitly. Though I suspect you will need to use screen because of the inability to foreground the app.

For screen, this is an example of what you are looking for

$ screen -S myScreen -d -m ./dostuff.sh
$ screen -r myScreen
Related Question