joelc
joelc

Reputation: 331

Running a linux service from Java

I am trying to start and stop a linux service from Java. I am using ProcessBuilder as per current accepted practices. I have constructed the following code (webService is a parameter containing the name of the service being started):

String[] commands = new String[6]; 

commands[0] = "/bin/sh";
commands[1] = "-c";
commands[2] = "sudo";
commands[3] = "service";
commands[4] = webService;
commands[5] = "start";

ProcessBuilder processBuilder = new ProcessBuilder(commands);

Process process = processBuilder.start();

int outcomeOfProcess = process.waitFor();

This effectively is calling the command /bin/sh -c sudo service webService start. Which when run from the linux terminal of the server runs fine however doesn't work from Java ProcessBuilder (outcomeOfProcess is 1 when this is run).

I have tried sudo systemctl start webservice.service as well with no avail - and I also have tried to call a bash script already located on the linux machine but this doesn't work either.

Does anyone have any ideas of how this can be fixed?

Upvotes: 0

Views: 2218

Answers (2)

joelc
joelc

Reputation: 331

The problem was the sudoers file which prevented the code executing without a tty changing this file slightly meant that it would accept code. Nightmare debugging this as it has taken all day! thanks for all the input!

Upvotes: 0

Jordi Castilla
Jordi Castilla

Reputation: 26961

Not sure ProcessBuilder can handle SO requests. For cases I need to execute host OS commands (Windows/OSX/Linux etc..), I use Runtime.exec(String):

String command = "/bin/sh -c sudo service " + webService  + " start";
Runtime.getRuntime().exec(command);

If you also want to get the output and error exit you can use Process and BufferedReader as described in this answer.

public static void main(String args[]) {
    String s;
    Process p;

    String command = "/bin/sh -c sudo service " + webService  + " start";

    try {
        // run the command
        p = Runtime.getRuntime().exec(command);
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        // get the result
        while ((s = br.readLine()) != null)
            System.out.println("line: " + s);
        p.waitFor();
        // get the exit code
        System.out.println ("exit: " + p.exitValue());
        p.destroy();
    } catch (Exception e) {}
}

NOTE: not a Linux expert, so I can't tell 100% your command line is correct, but yes you can execute it in this way.

Upvotes: 1

Related Questions