Linux check java process

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.

Источник

Java — how to check whether another (non-Java) process is running on Linux

I’m having some weird problems with this.

We are using Xvfb virtual desktop manager and want to make sure it’s running before I continue. Using pure shell, I could do this easily:

And that gives me exactly what I need, a single line containing information about the Xvfb proc. Next, I want to incorporate this into my Java program and parse the results and store the PID of the running Xvfb process. So I am trying this:

The bizarre thing is that if I use «ps -ef», I get a huge list of processes dumped to my console when I run my app. But if I use | grep to narrow the list of processes returned, I get zero results. input.readLine() gets null every time.

Читайте также:  Драйвер для rtl8821ce linux

I have also tried:

To just grab the process id. Also, no luck.

Has anyone else experienced this or know what I’m doing wrong?

4 Answers 4

You’re trying to use the «|» which is a pipe function that is particular to the shell, therefore you cannot do it in the java process. You could just try getting the process ID by using pidof Xvfb .

Maybe Runtime.getRuntime().exec() tries to execute the program as it is in the argument. That is, it runs the program ps with arguments -ef , | , grep , etc. And so, the program fails because it does not understand what’s going on.

If you need to run piped commands, you should call the shell explicitly:

When you execute your command string directly you do not get a shell and it is the shell which handles the pipes. So, you would execute something like «/bin/sh -e \»ps -ef | grep Xvfb | grep -v grep\»»

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 if 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 on with Java?! :).

Источник

Как найти мой PID в Java или JRuby на Linux?

Мне нужно найти PID текущего запущенного процесса на платформе Linux (это может быть зависимое системное решение). Java не поддерживает получение идентификатора процесса, и JRuby в настоящее время имеет ошибку с методом Ruby, Process.пид-регулятор.

есть ли другой способ получить PID?

6 ответов

Если у вас procfs установлен, вы можете найти идентификатор процесса через символическую ссылку /proc/self, которая указывает на каталог, имя которого является pid (здесь также есть файлы с другой соответствующей информацией, включая PID, но каталог-это все, что вам нужно в этом случае).

таким образом, с Java, вы можете сделать:

в JRuby вы можете использовать одно и то же решение:

специальные спасибо канал #stackoverflow на свободном узле для помогите мне решить эту проблему! (в частности, Jerub, gregh и сайт topdeck)

тестируется только в Linux с помощью Sun JVM. Может не работать с другими реализациями JMX.

вы можете использовать интерфейс JNI для вызова функции POSIX getpid(). Это довольно прямолинейно. Вы начинаете с класса для функций POSIX, которые вам нужны. Я называю это POSIX.java :

скомпилировать его с

после этого вы создаете заголовочный файл POSIX.h С

файл заголовка содержит прототип C для функции с обертыванием функции getpid. Теперь вам нужно реализовать функцию, которая довольно простой. Я сделал это в POSIX.c :

Читайте также:  Tool new windows 10

теперь вы можете скомпилировать его с помощью gcc:

вы должны указать место где установлена платформа Java. Вот и все. Теперь вы можете использовать его. Создайте простую программу getpid:

скомпилировать его с javac getpid.java и запустить его:

первый pid написан оболочкой, а второй написан программой Java после того, как приглашение оболочки вернулось. ∎

Spawn процесс оболочки, который будет читать pid своего родителя. Это должно быть наш пид. Вот рабочий код, без исключения и обработка ошибок.

Это решение кажется лучшим, если PID должен быть получен только для выдачи другой команды оболочки. Достаточно обернуть команду в обратные кавычки, чтобы передать ее в качестве аргумента другой команде, например:

Это может заменить последнюю строку в массиве, заданном exec звонок.

вы можете попробовать getpid() в JNR-Posix.

Он также имеет оболочку Windows POSIX, которая вызывает getpid () от libc. Нет необходимости в JNI.

Java 9 наконец предлагает официальный способ сделать это с ProcessHandle:

сначала получает ProcessHandle ссылка для текущего процесса.

для того, чтобы получить доступ к его pid .

Источник

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.

Читайте также:  Системный вызов system linux

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?! :).

Источник

Check if process is running on windows/linux

i have a process

i want to keep a check on this process whether its running or has crashed in case of crash want to restart it, this Process can have multiple instance available depending upon the port

Can i trace this thing on Linux as well as on windows? Read some articles on it but this 1 is bit different, since it involves multiple occurrences and have to check on some particular process only

7 Answers 7

You can do a p.waitFor() so the thread that executed the statement waits till the process is complete. You can then do the cleanup/restart logic right after, as that code will get executed when the process dies. However I am not sure how this would work if the process hangs instead of dying, but this could be worth a try. By the way I would recommend using Java Service Wrapper and supervisord in your case if this is something you’re going to do on production.

As of Java 8 you can do:

For pre Java 8 code, I’m using reflection with a fallback to catching IllegalThreadStateException . The reflection will only work on instances of ProcessImpl , but as that’s what’s returned by ProcessBuilder it’s usually the case for me.

Java 5 and on have a way to handle this using java.util.concurrent.Future.

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future and return null as a result of the underlying task.

Источник

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