LiteFine Dev
LiteFine Dev

Reputation: 33

How to start multiple jars using linux screens?

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?

Upvotes: 2

Views: 2299

Answers (1)

Hugues M.
Hugues M.

Reputation: 20467

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();
}

Upvotes: 3

Related Questions