Unpossible
Unpossible

Reputation: 623

bash kill process if it takes too long to shutdown

I have a group of supervisord run process that I want to automate starting and stopping with a script. But sometimes the supervisor shutdown command takes too long to complete and wait times start to pile up. Currently I am doing:

     for each in "${args[@]}"; do
             (supervisorctl -c configs/supervisord_${each}.conf shutdown) & sleep 8s & (kill -9 `ps aux | grep supervisor| grep ${each} | a    wk '{print $2}'` && kill -9 `ps aux | grep supervisor| grep ${each} | awk '{print $2}'`)
         done

Is there a cleaner way I can kill the supervisor process, after a few seconds, if it takes too long to stop? To be clear, I am trying to kill the supervisor process that I am trying to shutdown with supervisorctl -c {config path} shutdown, and not the supervisorctl shutdown command itself.

Upvotes: 3

Views: 1739

Answers (1)

Luis Colorado
Luis Colorado

Reputation: 12698

Well, if you have a look at bash(1) (or sh(1) in case you use plain bourne shell) you will see that there's a variable $! that stores the pid of the last background executed command (&), so you can substitute the body of the loop with:

supervisorctl -c configs/supervisrod_${each}.conf shutdown &
pid_to_kill=$!
(sleep 8; kill -9 "${pid_to_kill}") &

searching the process table is an expensive operation that you should avoid. Remember also that a kill -9 doesn't allow the program to close cleanly, and you can probably miss some data.

SECOND TRY

If you want to kill the supervisor (and not the supervisorctl you use to control it) you can simply check if it writes some pid file in /var/run directory. As it is common use, if you need an unrelated process (like supervisorctl, with no parental father-to-child relationship) to get access to its pid and be able to send signals to it.

Upvotes: 2

Related Questions