xtrafrancyz

Supervisor'ed dynamic pid

Aug 1st, 2018
182
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env bash
  2. # Signals from the supervisor are not propagated to the child processes
  3.  
  4. set -eu
  5.  
  6. if [[ $# -eq 0 ]] ; then
  7.     echo "Usage $0 <pid_file> <command> [with arguments]"
  8.     exit 0
  9. fi
  10.  
  11. pidfile=$1
  12. command="${@:2}"
  13.  
  14. # Proxy signals
  15. function trap_sigterm(){
  16.     kill -SIGTERM $(cat $pidfile)
  17.     sleep_while_process_is_alive 0.1
  18.     exit 0
  19. }
  20. trap trap_sigterm SIGTERM SIGINT
  21.  
  22. function trap_sigusr2() {
  23.     kill -SIGUSR2 $(cat $pidfile)
  24. }
  25. trap trap_sigusr2 SIGUSR2
  26.  
  27. function sleep_while_process_is_alive() {
  28.     while [ -f $pidfile ] ; do
  29.         PID=$(cat $pidfile)
  30.         if [ -n "$PID" -a -e /proc/$PID ]; then
  31.             sleep $1
  32.         else
  33.             return
  34.         fi
  35.     done
  36. }
  37.  
  38. # Run command in background
  39. $command &
  40.  
  41. # Wait until pid is created
  42. sleep 2
  43.  
  44. # Loop while the pidfile and the process exist
  45. sleep_while_process_is_alive 0.5
  46.  
  47. # Exit unexpected
  48. exit 1000
RAW Paste Data