1

I'm writing a plugin in order to restart a server application on Linux (though I'm testing on OSX). The way I'm doing this is using a shell script which commands the application to stop, and then oversees the death of the process, safely starting a new one when the time comes.

My script works when I execute it manually from the command line. However, when I execute it from within the application, the shell process is killed along with the application.

I've tried two different methods of running the process from Java:

String scriptArgs[] = {"sh", "restart.sh", "&"};

    try {
        Runtime.getRuntime().exec(scriptArgs);
    } catch (IOException e) {
        e.printStackTrace();
    }

and

ProcessBuilder processBuilder = new ProcessBuilder("sh", "restart.sh");
    try {
        processBuilder.directory(new File(System.getProperty("user.dir")));
        processBuilder.redirectErrorStream(false);
        processBuilder.start();
    } catch (IOException e) {
        e.printStackTrace();
    }

Both of these methods gave the same result: the script was called, it successfully shut down the application, and then it died before it could continue. Is there any method to start a completely independent process from Java?

2
  • 3
    have you tried nohup? Commented Jun 11, 2014 at 3:32
  • Thank you, I had never heard of nohup, but that's exactly what I needed. Post this as an answer and I will accept it! Commented Jun 12, 2014 at 1:35

1 Answer 1

2

When you run a process from java you are creating a shell instance which then runs the process. The shell will only exit once this process has finished even if it is being run in the background &

To run a process in headless mode you need to use the nohup command. For details, see here.

A usage could look like this:

ProcessBuilder processBuilder = new ProcessBuilder("nohup", "sh", "restart.sh");
try {
    processBuilder.directory(new File(System.getProperty("user.dir")));
    processBuilder.redirectErrorStream(false);
    processBuilder.start();
} catch (IOException e) {
    e.printStackTrace();
}
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.