2

I want to start some jars in linux from Java runtime. From the command line of Linux it would look something like this:

> screen -S jar1
> java -jar Something1.jar
> Ctrl + AD
> screen -S jar2
...

How i can do this using Java?

Hugues M.
  • 19,846
  • 6
  • 37
  • 65
  • 1
    You cannot. However you can take a look at `screen`'s command line options, to achieve the `^AD` shortcut's functionality... – Usagi Miyamoto Aug 30 '17 at 08:04
  • you could use the robot api to send key combination. Look [here](https://stackoverflow.com/questions/14595483/using-java-to-send-key-combinations) for example. – ArcticLord Aug 30 '17 at 08:07

1 Answers1

3

To start a screen with its own session & command, directly detached, you can do this:

screen -dmS jar1 bash -c "java -jar jar1.jar"

That's from the command line, where screen will fork a new process that executes in the background so after running the above you are back in your interactive shell. But from another program you would use -D instead of -d, for example with Java you probably want the ability to waitFor() on the process you start.
From man screen:

-d -m Start screen in "detached" mode. This creates a new session but doesn't attach to it. This is useful for system startup scripts.
-D -m This also starts screen in "detached" mode, but doesn't fork a new process. The command exits if the session terminates.

Example with 2 dummy long-running commands:

% screen -dmS app-top top

% screen -dmS app-foo bash -c "while sleep 1; do date; done"

% screen -ls
There are screens on:
        25377.app-foo   (08/30/2017 09:26:24 AM)        (Detached)
        24977.app-top   (08/30/2017 09:23:41 AM)        (Detached)

Tree of processes:

SCREEN -dmS app-foo bash -c while sleep 1; do date; done
 \_ bash -c while sleep 1; do date; done
    \_ sleep 1
SCREEN -dmS app-top top
 \_ top

So from Java, something like this:

private Process runInScreen(String sessionName, String command) throws IOException {
    return new ProcessBuilder("screen", "-DmS", sessionName, "bash", "-c", command).inheritIO().start();
}
Hugues M.
  • 19,846
  • 6
  • 37
  • 65