How to Use Java to Get a List of Running Processes in Linux

In linux, the ps command can be used to get a list of running processes. Type the following command in a linux console.

ps -e -o command

The above command prints all running processes including the processes owned by other users (as specified by the -e option). The -o command flag instructs ps to show only the command name in the output. The command name contains the full path to the command including any command line arguments passed to it. If you just need the command name only (no path and arguments) replace the command keyword with comm.

How to Get All Running Processes in Linux – Java Example

In Java, you can use the Runtime class to execute any linux command. The following sample program in Java shows the use of Runtime class to get a list of all running processes in linux.

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

// Displays all running processes in linux.
public class ShowProcessesInLinux {

    public static void main(String[] args) throws Exception {
        printAllProcesses();
    }
    // Java example program to display the names of all running linux processes
    private static void printAllProcesses() throws Exception{
        // -e - show all processes including processes of other users
        // -o command - restrict the output to just the process name
        Process process = Runtime.getRuntime().exec("ps -e -o command");
        BufferedReader r =  new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;

        while((line=r.readLine())!=null) {
            System.out.println(line);
        }
    }
}

The ps command in linux is powerful and has many options. You can use various options to sort processes based on memory usage or cpu usage.

ps -e –sort=-pcpu -o pcpu,command

The above command lists all the processes sorted in the descending order of the cpu usage. Using the -o option, we can display only the cpu usage percentage and the full command for the process (including arguments and path).

ps -e –sort=-size -o size,command

The above command lists all the processes sorted in the descending order of the memory taken by the process. Using the -o option, we display only the memory usage and full command of the process. The memory displayed is in Kilobytes.

The following example Java program shows how we can use the above command to display the process with the highest cpu usage. This program itself may reported as the top cpu process since it is running when the ps command is executed!

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

// Sample Java program to print highest CPU process in a linux system
// Note that this program itself may be reported as the top process!
public class TopCPULinuxProcess {

    public static void main(String[] args) throws Exception {
        printProcessWithHighestCPU();
    }

    // Java example program to print the name of the process with highest CPU usage in linux
    private static void printProcessWithHighestCPU() throws Exception {
        Process process = Runtime.getRuntime().exec("ps -e --sort=-pcpu -o pcpu,command");
        BufferedReader r =  new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        int rowCount = 1;
        while((line=r.readLine())!=null) {
            if(rowCount==2) break; //first row is header
            rowCount++;
        }
        line = line.trim(); // remove spaces in the beginning
        int firstSpacePos = line.indexOf(" ");
        String cpuUsage = line.substring(0, firstSpacePos);
        String processName = line.substring(firstSpacePos+1);
        System.out.println("Process with highest CPU="+processName);
        System.out.println("CPU%="+cpuUsage);
    }
}

The following Java program will print the top 5 processes with the highest memory usage. Please note that the reported memory usage may not be exact in linux,

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

// Displays the top 5 processes with the highest memory usage in linux
public class Top5MemoryProcessesInLinux {
    public static void main(String[] args) throws Exception {
        printTop5MemoryProcesses();
    }

    // Java method to print top 5 processes with highest memory usage in linux
    private static void printTop5MemoryProcesses() throws Exception {
        Process process = Runtime.getRuntime().exec("ps -e --sort=-size -o size,command");
        BufferedReader r =  new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        int rowCount = 0;
        while((line=r.readLine())!=null) {
            System.out.println(line);
            rowCount++;
            if(rowCount>5) break; // note that first line is the header
        }
    }
}

The following sample Java program will print verbose information about all the processes running in a linux system,

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

// Displays a verbose report of all running processes in linux.
public class VerboseProcessReportInLinux {
    public static void main(String[] args) throws Exception {
        printVerboseProcessReport();
    }

    // Java program to print verbose process information.
    private static void printVerboseProcessReport() throws Exception {
        Process process = Runtime.getRuntime()
                .exec("ps -e --sort=-pcpu -o pcpu,size,flags,lim,lstart,nice,rss,start,state,tt,wchan,command");
        BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;

        while ((line = r.readLine()) != null) {
            System.out.println(line);
        }
    }
}

The above examples should work in common linux distributions such as Xubuntu, Ubuntu, CentOS, Fedora, OpenSUSE and Debian.

References

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply