Search code examples
javaunixprocesspid

Find unix command PID from Java


It is very easy to get the PID of previous process in unix-

echo $!

But, suppose I execute a unix command via Java-

Process process=Runtime.getRuntime().exec("myScript.sh");

Now, how do I now get the PID of "myScript.sh" also through Java ??

e.g.- In Unix, we would do- 1. Execute myScript.sh 2. Execute ps -ef | grep -i "myScript.sh" | grep -v grep

Output would be like-

     UID   PID  PPID   C    STIME TTY         TIME CMD
userprod 11764 28386   0 05:57:45 pts/3       0:01 myScript.sh

What I require through Java is the PID, which in this case is "11764".

p.s.- the script will also be executed from Java, not from shell.


Solution

  • not sure if this works;

    that process(Process process=Runtime.getRuntime().exec("myScript.sh"))
    

    is a java.lang.UNIXProcess and it has a field pid; use reflection to get the value