javashellruntimegarbage

Java Runtime getting a Garbage option error


i want to search for certain process through my java app so that i can verify if my app is running (Apache). here is a simplification of the class.

package com.tecsys.sm.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.tecsys.sm.util.FinalValues;

public class ShellRuntimeCommands {
    public static void showApacheProcess(){
        try {
            String command = "ps ax | grep \"/apps/apache/2.4.4/bin/httpd\" | grep -v \"grep\"";
            System.out.println("La commande est: " + command);
            final Process proc = Runtime.getRuntime().exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            String line = br.readLine();
            System.out.println("The Error line is "+line);
            String status;
            if(line!=null && line!=""){
                status = FinalValues.STARTED_STATUS;
            }else{
                status = FinalValues.STOPPED_STATUS;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static void main(String[] args){
    ShellRuntimeCommands.showApacheProcess();
    }
}

Here's the output:

La commande est: ps ax | grep "/apps/apache/2.4.4/bin/httpd" | grep -v "grep"
The line is ERROR: Garbage option.

The thing is that i copy paste the string command of the output and i execute in the terminal, it works fine, but it's not working through java runtime.


Solution

  • The problem are the pipes which are a feature of a shell, so Runtime.exec does not support them. Here is the workaround: How to make pipes work with Runtime.exec()?