Get process list in Unix based systems in Java

In this article we’ll talk about how to get process list in Java by running standard Unix commands.

Lets check out the example of checking work of the java application. One
of the solution could be the jvmstat. It’s a reliable and powerful tool,
but much simpler and faster solution is to use standard Unix command
‘ps’: you can execute it like any other command by using exec() method
of java.lang.Runtime class.
If you want to check the work of java application, run ‘ps’ command with
‘-ef’ options, that will show you not only the command, time and PID of
all the running processes, but also the full listing, which contains
necessary information about the file that is being executed and program
parameters. Otherwise, if the list of PID and commands of running
processes is enough for you, run ‘ps -e’.

Here is the code I used in my application, hope it will be helpful.

String line;
//Executable file name of the application to check. 
final String applicationToCheck = "application.jar"
boolean applicationIsOk = false;
//Running command that will get all the working processes.
Process proc = Runtime.getRuntime().exec("ps -ef");
InputStream stream = proc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
//Parsing the input stream.
while ((line = reader.readLine()) != null) {
    Pattern pattern = Pattern.compile(applicationToCheck);
    Matcher matcher = pattern.matcher(line);
    if (matcher.find()) {
        applicationIsOk = true;
        break;
    }
}Code language: JavaScript (javascript)
Software Developer