Reputation: 10154
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);
}
Upvotes: 3
Views: 5159
Reputation: 9262
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.
Upvotes: 3