Bash store pid of command

Issue

I have a problem. I am trying to monitor a Java program. To do that I have a start/stop Bash script that looks like this:

#!/bin/bash
 case $1 in
    start)
       echo $$ > /var/script/myprogram/test.pid;
       (cd /var/script/myprogram/test; mvn exec:java)
       ;;
     stop) 
       kill $(cat test.pid);
       rm test.pid
       ;;
     *) 
       echo "usage: test {start|stop}" ;;
 esac
 exit 0

The problem is that the pid that I write in test.pid is not the pid number of the Java program, but the pid of the current Bash script. Is there a way to get the pid file of the started Java program and write that pid number to test.pid?

Solution

There are many reasons not to do what you are doing, but…a simple solution is to simply exec the java process so that the two pids are the same:

start)
   echo $$ > /var/script/myprogram/test.pid;
   cd /var/script/myprogram/test
   exec mvn exec:java
   ;;

exec will cause the current process to replace itself with the mvn process, so $$ is the correct pid. Also, this cleans up the process table, since the startup script no longer exists as the parent of the mvn.

Note that this is atypical behavior for a startup script, since it will not exit until the mvn process exits, but since this is what your original script is doing, it seems…still bizarre.

Answered By – William Pursell

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published