ritesh kumar
ritesh kumar

Reputation: 81

How to check , if a service is running on linux machine using java code

I want to check the status of a service running on linux. On machine i use the command "systemctl is-active service-name" to check the status of services.And it gives the output as active/inactive(when service is running/not running).

I want to get the status of the service in java. how i do that?

I tried this..

String SERVER_STATUS = new String[]{SUDO_COMMAND, "systemctl is-active vpnd.service"};
try {
    final Process process = new ProcessBuilder(SERVER_STATUS).start();
    process.waitFor();
    InputStream in = process.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String line = null;
    System.out.println("status: " + br.readLine());
} catch (IOException | InterruptedException e) {}

But br.readLine() is coming as null.

Upvotes: 0

Views: 3182

Answers (2)

James Joseph
James Joseph

Reputation: 11

Two things I found

  • Please split the command
  • Use absolute path of the command

Example

String SERVER_STATUS[] = new String[]{"sudo", "/usr/bin/systemctl", "is-active",  "java-linux-sample.service"};
        try {
            final Process process = new ProcessBuilder(SERVER_STATUS).redirectErrorStream(true).start();
            process.waitFor();
            InputStream in = process.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            //String line = null;
            System.out.println("status: " + br.readLine());
        } catch (Exception e)
          {
          e.printStackTrace();
          }

Upvotes: 1

flakes
flakes

Reputation: 23624

I assume this is because there is an error running the application. Does your java process have permissions to run systemctl? Is it failing to find the service?

I would advise that you also check the exit value and then check the appropriate error stream.


For example on a Windows machine if I make a mistake in the cmd command

String[] SERVER_STATUS_COMMAND = {"cmd.exe", "/c", "echoo foobar"};

Your program will write

status: null

If we tweak the application slightly we can have the error stream redirected to the output:

final Process process = new ProcessBuilder(SERVER_STATUS_COMMAND)
    .redirectErrorStream(true)
    .start();

then the program would write:

status: 'echoo' is not recognized as an internal or external command,

Upvotes: 0

Related Questions