How can I find out, which jar-files java is currently running (and their PIDs)?

I have a .jar file which is notorious for malfunctions. When a malfunction occurs, only a restart helps. I have a way to detect that malfunctions (reading the log-file of said .jar) So I want to write a script, that kills the process whenever the malfunction occurs. The problem is:

confus@confusion:~$ ps -A
...
4438 ?        00:00:00 java
4439 ?        00:00:00 java
4443 ?        00:00:00 java
...

The process name of all running .jars is naturally "java". How do I find out, which of these "java"-processes is the one I want to kill, i.e. the one running foobar.jar?


Solution 1:

You can run the lsof command, which lists which processes has open files, with your jar file given as an argument. An example viewing a file with less:

egil@mutter:~$ lsof foo.c
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF     NODE NAME
less    18871 egil    4r   REG    8,2        0 53862540 foo.c
egil@mutter:~$

To easily reuse the pid in a script, you could run it in terse mode:

egil@mutter:~$ lsof -t foo.c
18871

Or use it with the pids of the several java processes:

 $ lsof -p 4438

Solution 2:

Using ps ax will help.

It will display the process tree in a BSD style which simply shows way more information.

To find your particular process you just have to grep for the JAR name. ps ax | grep JARNAME will do it.

Solution 3:

You can do this native or if "lsof" is not installed via /proc//fd Example:

ps -ef|grep -w java
...
0c4       6917  6916  0 12:22 pts/7    00:00:00 java
...

ls -la /proc/6917/fd/
total 0
dr-x------ 2 0c4 svauser  0 Apr  2 12:23 .
dr-xr-xr-x 9 0c4 svauser  0 Apr  2 12:22 ..
lrwx------ 1 0c4 svauser 64 Apr  2 12:23 0 -> /dev/pts/7
lrwx------ 1 0c4 svauser 64 Apr  2 12:23 1 -> /dev/pts/7
lrwx------ 1 0c4 svauser 64 Apr  2 12:23 2 -> /dev/pts/7
lr-x------ 1 0c4 svauser 64 Apr  2 12:23 3 -> /opt/jdk1.8.0_191/jre/lib/rt.jar
lr-x------ 1 0c4 svauser 64 Apr  2 12:23 4 -> /media/veracrypt1/Downloads/rr/testone.jar
lr-x------ 1 0c4 svauser 64 Apr  2 12:23 5 -> /usr/share/java/gnu-getopt-1.0.14.jar