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?