The inimitable Wincent recently referred to a memcached script he had written that toggled whether memcached is running or not. I thought that was a great idea so wrote my own and in the spirit of comparing dicks I thought I’d post it here.
#!/usr/bin/env ruby = ::File.expand_path(::File.dirname(__FILE__)) + '/../tmp/memcached.pid' def process_id File.exist?() ? File.read().to_i : false end def running? if process_id Process.kill(0, process_id) == 1 rescue false else false end end def start! print 'starting memcached ...' system "memcached -d -P #{} -l 127.0.0.1" sleep 0.5 print "started with pid #{File.read}" end def stop! print 'stopping memcached ...' Process.kill('INT', process_id) sleep 0.5 File.delete() if File.exist?() print 'done.' puts end def ensure_running running? ? puts('already running.') : start! end def ensure_stopped !running? ? puts('not running.') : stop! end def toggle running? ? stop! : start! end case ARGV.first when 'start' ensure_running when 'stop' ensure_stopped when 'toggle' toggle when 'status' running? ? puts('running') : puts('not running') else toggle end
I love writing these kinds of scripts in Ruby. It’s perfect for it.
November 20th, 2009 at 7:54 am
Let us compare, then. Here’s the script I mentioned:
Mine doesn’t have “start”, “stop” and “toggle” actions like yours does; its default action is to toggle.
As for “status”, I actually have a script/status script that shows me a summary like:
November 20th, 2009 at 1:06 pm
Thanks for the interesting counter-example. That’s certainly a lot cleaner than my bloated efforts. Cool, and instructive, use of pathname.
I’m a little more paranoid in my checks there since I have been burnt a few times by assuming the existence of a pidfile means the process is actually running; perhaps as I see it run reliably a little more I’ll be more trusting.
November 20th, 2009 at 3:58 pm
Yes, know what you mean about paranoid. Evidently on the production environment I wouldn’t use such a naïve little script, but I use Monit instead.