Search code examples
rubyunixcapistrano

Capistrano Task to kill a process by port ONLY IF the process is running?


I pretty much need what my Question statement says, currently I have a Capistrano task that looks like this:

desc "stops private pub"
task :stop_private_pub do
  run "kill -9 $(lsof -i:9292 -t)"
end
before 'deploy', 'servers:stop_private_pub'

...And it works well when in fact the process in port 9292 is running, The problem is that when the process Isn't running this task will FAIL! and it Halts the whole Deployment Process!

I'm not a UNIX Shell expert, nor am I a Capistrano master, so.. I really need help improving this Capistrano Task, Is there a way to kill -9 only if the process is running?

How can I do this?

Thanks in advance.


Solution

  • You could use Capistrano's capture command (in V3 at least, probably a V2 equivalent) to grab the output from your lsof command, and then only if you get a PID run the kill command.

    pid = capture 'lsof', '-i:9292', '-t'
    if pid # ensure it's valid here
       run "kill -9 #{pid}" # make darn sure pid is an integer if you embed it
    end