tags:

views:

59

answers:

1

I need to find the pid of a certain java process in bash on linux.

If there's only one java process,

PID=$(pgrep java)

works.

For multiple java processes it becomes more complicated. Manually, I run pstree, find the ancestor of the java process that I need first, then find the java process in question. Is it possible to do this in bash? Basically I need the functionality that in pseudo-code looks like:

Having `processname1` and `processname2`
and knowing that `processname2` is in the subtree of 'processname1',
find the pid of `processname2`.

In this example the java process will be processname2.

+2  A: 

Reformulating your psuedo-code question: find all processname2 processes which have a processname1 process as parent. This can be directly expressed using the following nested pgrep call:

pgrep -P $(pgrep -d, processname1) processname2

Here's the documentation for those flag straight from the pgrep(1) manpage:

  -d delimiter
         Sets the string used to delimit each process ID in the output
         (by default a newline).

  -P ppid,...
         Only match processes whose parent process ID is listed.

Note that this will only work if processname2 is an immediate child process of processname1.

earl
I'm confused a bit by the description of -P in the man page. Would this work if `processname2` is not a direct child of `processname1`, but a grandchild etc (so there are other intermediary processes in the chain between them)? A quick experiment in the console shows that your recipe works only when `processname2` is a direct child.
jedi_coder
Nope, this only works for direct child/parent processes. Added a remark to that effect.
earl