3

Im trying to run a shell script in the background that does not terminate when my function/process end. However it seems that despite nohup, when the java thread ends. So does the script.

Below is sample code.

///
/// Tries to run a script in the background
///
try {
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("nohup sh ./runner.sh > output.txt &", new String[] {}, wrkDir);
    // pr.waitFor(); // Intentionally not using
} catch(Exception e) {
    throw new RuntimeException(e);
}

1 Answer 1

3

nohup applies to invocations from the shell, not from a calling program.

There are probably a lot of ways to solve this, but one that springs to mind is to try modifying your Java code to invoke a launcher shell script that invokes the nohup runner.sh... code (without needing to launch sh).

Something like this (untested) code:

Revised Java:

///
/// Tries to run a script in the background
///
try {
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("sh ./launcher.sh", new String[] {}, wrkDir);
    // pr.waitFor(); // Intentionally not using
} catch(Exception e) {
    throw new RuntimeException(e);
}

launcher.sh

#!/bin/sh

nohup ./runner.sh > output.txt &

I'm not sure about the redirection here, but if this works (as I mentioned, this solution is untested), the downside would be that you lose feedback from attempting to invoke runner--any errors in that script invocation will be unavailable to your Java process.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.