Linux посмотреть процессы java

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.

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.

Читайте также:  Отражение

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).

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.

Читайте также:  Python function anonymous function

References

Источник

Find all the Java processes running on your machine

When your application has some problem, the first thing to check is running processes on the machine. For Linux OS we generally use ps -ef . ps is one of the most used Linux troubleshooting commands. JDK provides similar functionality for Java processes through jps . The jps command-line utility provides a list of all running Java processes on a machine for which the user has access rights. The access rights are determined by access-control mechanisms specific to the operating system. jps utility can also provide information on arguments passed to the main method, arguments passed to JVM, etc. In this post, we will see the functionalities provided by jps .

Troubleshooting a Java Application with jps

In this section, we will see how to use jps with a running Java process.

jps command

jps [options] pid options: This represents the jps command-line options. pid: The process ID for which the information specified by the options is to be printed. 

Java program we will be debugging in this post

Following is the sample class we are going to debug and try to understand the different features available.

public class Test  public static void main(String[] args)  while(true)  > > > 

For all our examples we will be using Java 17, as of writing this post it is built using JDK master branch. This post explains how to build JDK from the source.

java -version openjdk version "17-internal" 2021-09-14 OpenJDK Runtime Environment (build 17-internal+0-adhoc.vipin.jdk) OpenJDK 64-Bit Server VM (build 17-internal+0-adhoc.vipin.jdk, mixed mode) 

We are running the Java process using the following command. For rest of the blog post we will use jps on this process.

java -XX:ConcGCThreads=6 -Xmx256m -Xms8m -Xss256k Test argument1 argument2 

Following command shows process ids.

2468 10660 7067 7470 10366 

This is the command to list Java processes with main class names, it is same as command jps -V .

2468 10694 Jps 7067 Main 7470 Launcher 10366 Test 

jps -l displays the full package name for the application’s main class or the full pathname to the application’s JAR file.

2468 10554 jdk.jcmd/sun.tools.jps.Jps 7067 com.intellij.idea.Main 7470 org.jetbrains.jps.cmdline.Launcher 10366 Test 

jps -m displays the arguments passed to the main method

2468 10726 Jps -m 7067 Main 7470 Launcher /home/vipin/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/203.7148.57/lib/commons-lang3-3.10.jar:/home/vipin/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/203.7148.57/lib/httpclient-4.5.12.jar:/home/vipin/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/203.7148.57/lib/annotations.jar:/home/vipin/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/203.7148.57/lib/netty-buffer-4.1.52.Final.jar:/home/vipin/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/203.7148.57/plugins/java/lib/jps-javac-extension-1.jar:/home/vipin/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/203.7148.57/lib/jdom.jar:/home/vipin/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/203.7148.57/lib/netty-resolver-4.1.52.Final.jar:/home/vipin/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/203.7148.57/lib/maven-resolver-api-1.3.3.jar:/home/vipin/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/203.7148.57/plugins/java/lib/maven-resolver-connector-basic-1.3.3.jar:/home/vipin/.local/share/JetBrains/Toolbox/apps/IDE 10366 Test argument1 argument2 

jps -v displays the arguments passed to the JVM.

2468 -Djava.library.path=/tmp/.mount_jetbraH5N0hQ -Xmx256m -Xms8m -Xss256k -XX:+UseStringDeduplication -XX:+UseCompressedOops -XX:+UseSerialGC -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Djdk.lang.processReaperUseDefaultStackSize=true vfprintf exit abort -DTOOLBOX_VERSION=1.20.7940 10501 Jps -Dapplication.home=/home/vipin/githubprojects/jdk/build/linux-x86_64-server-release/jdk -Xms8m -Djdk.module.main=jdk.jcmd 7067 Main -Xms128m -Xmx2048m -XX:ReservedCodeCacheSize=512m -XX:+UseConcMarkSweepGC -XX:SoftRefLRUPolicyMSPerMB=50 -XX:CICompilerCount=2 -XX:+HeapDumpOnOutOfMemoryError -XX:-OmitStackTraceInFastThrow -ea -Dsun.io.useCanonCaches=false -Djdk.http.auth.tunneling.disabledSchemes="" -Djdk.attach.allowAttachSelf=true -Djdk.module.illegalAccess.silent=true -Dkotlinx.coroutines.debug=off -Dsun.tools.attach.tmp.only=true -Dide.no.platform.update=true -XX:ErrorFile=/home/vipin/java_error_in_idea_%p.log -XX:HeapDumpPath=/home/vipin/java_error_in_idea_.hprof -Didea.vendor.name=JetBrains -Didea.paths.selector=IdeaIC2020.3 -Djb.vmOptionsFile=/home/vipin/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/203.7148.57.vmoptions -Didea.platform.prefix=Idea -Didea.jre.check=true 7470 Launcher -Xmx700m -Djava.awt.headless=true -Djdt.compiler.useSingleThread=true -Dpreload.project.path=/home/vipin/githubprojects/jdk -Dpreload.config.path=/home/vipin/.config/JetBrains/IdeaIC2020.3/options -Dcompile.parallel=false -Drebuild.on.dependency.change=true -Dio.netty.initialSeedUniquifier=4046065713679813272 -Dfile.encoding=UTF-8 -Duser.language=en -Duser.country=IN -Didea.paths.selector=IdeaIC2020.3 -Didea.home.path=/home/vipin/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/203.7148.57 -Didea.config.path=/home/vipin/.config/JetBrains/IdeaIC2020.3 -Didea.plugins.path=/home/vipin/.local/share/JetBrains/IdeaIC2020.3 -Djps.log.dir=/home/vipin/.cache/JetBrains/IdeaIC2020.3/log/build-log -Djps.fallback.jdk.home=/home/vipin/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/203.7148.57/jbr -Djps.fallback.jdk.version=11.0.9.1 -Dio.netty.noUnsafe=true -Djava.io.tmpdir=/home/vipin/.cache/JetBrains/IdeaIC2020.3/compile-server/jdk_5c2ba8e3/_temp_ -Djps.backward.ref.index.builder=true -Dkotlin.incremental.compilation=true 10366 Test -XX:ConcGCThreads=6 -Xmx256m -Xms8m -Xss256k 

jcmd to list Java processes

jcmd or jcmd -l both provides similar information as jps -l . You can read more about jcmd on post.

Conclusion

jps is a simple tool with few options that make it easy to master, and when in need it can be a quick and great help you wanted. Utilities like this are very useful in a situation when we need to analyze and resolve problems in production Java application quickly. jps is part of OpenJDK, no need to install any third party software.

If you want to get amazing Java jobs, I wrote an ebook 5 steps to Best Java Jobs. You can download this step-by-step guide for free!

Источник

Оцените статью