Friday, August 30, 2013

Start process, get PID of just started process, and terminate the process by PID later

Ok, let's say we have a usecase - a job on Jenkins CI that needs to start a background process, remember PID of the process, pass the PID to some later cleanup. And we need something that will work on Linux and on Mac OS X (yes, even this OS can behave polite).

So 1st, let's start a process and remember it's PID. This is done via $! shell environment variable. The $! variable will have PID of latest started process. So here is an example:

nohup tail -f /var/log/syslog > /tmp/$BUILD_TAG.log & export LOGGER_PID=$! 
# $BUILD_TAG - is an environment variable provided by Jenkins CI, it has unique job execution identifier

2nd, let's remember the PID

echo -e "LOGGER_PID=$LOGGER_PID" > /tmp/$BUILD_TAG

3rd, let's use the PID and send SIGTERM to the process if it is still alive. We'll wrap it to a shell script.

#!/bin/bash
. /tmp/$BUILD_TAG  # read to LOGGER_PID env variable

kill_proc(){

  local pid_alive=`ps ax| awk '{print $1}' | grep -e "^$LOGGER_PID$" >>/dev/null; echo $?`;
   # ps ax| awk '{print $1}' - will print to stdout PIDs without surrounding spaces
   # grep -e "^$LOGGER_PID$" >>/dev/null; - will search for the PID, ^ and $ are important, just in case our PID is a substring of some other PID on system
   # echo $? - will echo exit code of last command
  if [ $pid_alive -eq 0 ]; then 
    kill $LOGGER_PID; # sending  SIGTERM to the process
    sleep 10;
  else
    echo "Proc with PID $LOGGER_PID already terminated" 
  fi;  
}

kill_proc;




No comments:

Post a Comment