Find the pid of a java process under Linux
using ps
ps
allows the user to define his own formatting for its output with the -o
switch, and -C
to select entries by the given command. I would go with:
ps -C java -o pid
from the man page:
-C cmdlist Select by command name This selects the processes whose executable name is given in cmdlist. -o format user-defined format. format is a single argument in the form of a blank-separated or comma-separated list, which offers a way to specify individual output columns. The recognized keywords are described in the STANDARD FORMAT SPECIFIERS section below. Headers may be renamed (ps -o pid,ruser=RealUser -o comm=Command) as desired. If all column headers are empty (ps -o pid= -o comm=) then the header line will not be output. Column width will increase as needed for wide headers; this may be used to widen up columns such as WCHAN (ps -o pid,wchan=WIDE-WCHAN-COLUMN -o comm). Explicit width control (ps opid,wchan:42,cmd) is offered too. The behavior of ps -o pid=X,comm=Y varies with personality; output may be one column named "X,comm=Y" or two columns named "X" and "Y". Use multiple -o options when in doubt. Use the PS_FORMAT environment variable to specify a default as desired; DefSysV and DefBSD are macros that may be used to choose the default UNIX or BSD columns.
One can get more accurate results by specifying more restrictions (ie the user under which the process runs, etc). Look at the man page for more information and other switches.
example:
$ sleep 10 &[1] 12654$ ps -C sleep -o pid12654
using the shell
I don't know why you use an .sh
script to run your code and not call java
directly, but if in any case you use the &
(background) operator, you can grab the pid
through your shell, with the $!
variable.
for example:
$ sleep 5 &[1] 12395$ echo $!12395
same goes for the java -jar .. &
command, $!
will be set to the pid of the last backgrounded job.
jps is the same as ps except it only looks at java processes.
If you then need the PID, you can do something like the following:
jps | grep JAVA_NAME | awk '{print $1}'
That runs jps, then uses grep to filter by the java application or jar you want to kill. After that, awk captures and prints just the pid to the console.