- Как получить точный список запущенных процессов в Linux из приложения Java?
- Quick Programming Tips
- How to Get All Running Processes in Linux — Java Example
- How to get list of running processes with Java
- 3 Answers 3
- Not the answer you’re looking for? Browse other questions tagged java linux or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- List of Java processes
- 18 Answers 18
- How to find a Java thread running on Linux with ps -axl?
- 8 Answers 8
Как получить точный список запущенных процессов в Linux из приложения Java?
Я делаю приложение, и одно из требований на данный момент — уметь искать процессы других запущенных приложений и при необходимости убивать их.
Я пробовал » jps «, который поставляется с JDK, и это именно то, что мне нужно. Идентификатор процесса приложения и настоящее имя приложения. Используя это, я могу убить по идентификатору процесса, а также сопоставить по имени, какие процессы мне действительно нужно завершить, не прерывая неправильные процессы. К сожалению, не все конечные пользователи этого приложения будут иметь JDK, поэтому jps не является надежным. Мне нужен другой способ сделать это.
Я пробовал много команд «ps», которые, кажется, не работают правильно. Например, на данный момент я использую
Это не помогает мне, так как не отображает имена процессов, а также не кажется точным. Когда я запускаю свои java-приложения из терминала, а затем перезапускаю программу, запущенные приложения не меняются, когда я ожидаю увидеть добавленный дополнительный процесс.
С Java в настоящее время я использую
Есть какой-либо способ сделать это? Или каким-то образом изолировать исполняемый файл jps, чтобы я мог упаковать его в свой проект и использовать в переносном поместье?
Когда я запускаю jps из JDK, я получаю этот вывод
Когда я запускаю ps -ef с моего машинного терминала, я получаю этот вывод
Когда я запускаю ps -ef из своего Java-приложения, я получаю следующее, а идентификатор процесса 11503 нигде не видно .
Проблема заключалась в / bin / sh -c в команде. Удаление этого дало мне правильный вывод, хотя я все еще думаю, что jps — лучшее решение (jps может быть изолирован, но окончательный размер составляет
Источник
Quick Programming Tips
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.
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!
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,
The following sample Java program will print verbose information about all the processes running in a linux system,
The above examples should work in common linux distributions such as Xubuntu, Ubuntu, CentOS, Fedora, OpenSUSE and Debian.
Источник
How to get list of running processes with Java
I want to get a list with all running processes using Java code?. Can you tell me from which file I can get this information? I would like to get his data from /proc filesystem.
3 Answers 3
Just parse the input obtained by running Process p = Runtime.getRuntime().exec(«ps -e»);
I assume you use linux since you have tagged the question with linux .
The numerically named folders in /proc contain information on the processes on your system.
Getting the contents of those into a human readable format would require some effort in directory traversal, reading documentation and code related to the /proc FS, and is too wide an area to go into detail with here, but concrete issues related to this would be great SO followup questions 🙂
Not the answer you’re looking for? Browse other questions tagged java linux or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
List of Java processes
How can I list all Java processes in bash? I need an command line. I know there is command ps but I don’t know what parameters I need to use.
18 Answers 18
and see how you get on
Recent Java comes with Java Virtual Machine Process Status Tool «jps»
is most useful. Prints just pid and qualified main class name:
Starting from Java 7, the simplest way and less error prone is to simply use the command jcmd that is part of the JDK such that it will work the same way on all OS.
Example:
jcmd allows to send diagnostic command requests to a running Java Virtual Machine (JVM).
More details about how to use jcmd .
You can use single command pgrep as well (doesn’t require you to use pipes and multiple commands):
For better output format check this command:
This will return all the running java processes in linux environment. Then you can kill the process using the process ID.
ps aux | grep java
$ ps -fea|grep -i java
If I want simply list java processes, use:
- show you all processes with long lines (arg: www)
- filter (grep) only lines what contain the word java, and
- filter out the line «grep java» 🙂
(btw, this example is not the effective one, but simple to remember) 😉
you can pipe the above to another commands, for example:
When I want to know if a certain Java class is getting executed, I use the following command line:
From the OS side view, the process’s command name is «java». The «ww» option widens the colum’s maximum characters, so it’s possible to grep the FQN of the related class.
jps & jcmd wasn’t showing me any results when I tried it using using openjdk-1.8 on redhat linux. But even if it did it only shows processes under the current user which doesn’t work in my case. Using the ps|grep is what I ended up doing but the class path for some java apps can be extremely long which makes results illegible so I used sed to remove it. This is a bit rough still but removes everything except: PID, User, java-class/jar, args.
Results look something like:
An alternative on windows to list all processes is:
But that is going to need some parsing to make it more legible.
There’s a lot of ways of doing this. You can use java.lang.ProcessBuilder and «pgrep» to get the process id (PID) with something like: pgrep -fl java | awk <'print $1'>. Or, if you are running under Linux, you can query the /proc directory.
I know, this seems horrible, and non portable, and even poorly implemented, I agree. But because Java actually runs in a VM, for some absurd reason that I can’t really figure out after more then 15 years working the JDK, is why it isn’t possible to see things outside the JVM space, it’s really ridiculous with you think about it. You can do everything else, even fork and join child processes (those were an horrible way of multitasking when the world didn’t know about threads or pthreads, what a hell! what’s going in on with Java?! :).
Источник
How to find a Java thread running on Linux with ps -axl?
I have a running JVM with two threads. Is it possible to see these running threads on my Linux OS with ps -axl ? I am trying to find out what priority the OS is giving to my threads. More info about this other issue here.
8 Answers 8
for finding your java process. Sample Output:
(6172 is id of your process) to get stack of threads inside jvm. Thread priority could be found from it. Sample output:
EDIT: If application running under different user than yourself (typical case on production and other non-local environments) then jps/jstack should be run via sudo. Examples:
On Linux, the Sun/Oracle JVM implements Java threads using native Linux threads, so yes, you can see them in «ps» output. Any thread belonging to a java process is a Java thread. But you won’t see the threads’ names, since those are specific to Java and the OS doesn’t know about them.
Linux threads do have IDs, but they’re just numbers, and «ps axl» doesn’t show them. «ps -eLf» does, in the «LWP» column. («LWP» is short for «lightweight process», which is another name for a thread.) Within Java, the Thread.getId() method might return the LWP number that you see in «ps -eLf» output, but I’m not sure.
All of the methods mentioned here work just fine. I was also searching for something similar and came across this blog by Timur Akhmadeev. I hope it helps.
As I was pointed by fellow programmers, the following is a summary of the post by Timur:
On a *nux based system first do a
to show you CPU usage on a per-thread basis. Look for user as oracle and in the command as Java. Note the PID for this process and then run
This brings up a list that displays all the tasks that the process(java program) is currently performing. After this we need to know what task each thread may be performing, for which we use a utility that the jdk provides, namely jstack. In linux, Java (JVM HotSpot) threads are mapped to threads that of the kerner.
Источник