From: Robert Klemme Date: 2009-12-13T23:10:32+09:00 Subject: Re: Is it possible to force a Ruby program to run as a proc name different than "ruby"? On 13.12.2009 13:55, Iñaki Baz Castillo wrote: > El Domingo, 13 de Diciembre de 2009, Robert Klemme escribió: >> On 13.12.2009 00:51, Iñaki Baz Castillo wrote: >>> El Sábado, 12 de Diciembre de 2009, Robert Klemme escribió: >>>> This is what I would do: >>>> >>>> VAR='/var/run' >>>> >>>> pid_file = File.join(VAR, File.basename($0) + '.pid') >>>> >>>> begin >>>> old_pid = File.read(pid_file).to_i >>>> Process.kill 0, old_pid >>>> $stderr.puts "ERROR: already running with PID #{old_pid}" >>>> exit 1 >>>> rescue Errno::ENOENT >>>> # no pid file >>>> rescue Errno::ESRCH >>>> # process not running >>>> $stderr.puts 'WARNING: stale pid file' >>>> end >>>> >>>> # open file with EXCL in order to catch race conditions where two >>>> # processes were started almost at the same time and both thought >>>> # they would be a new instance. Uncomment sleep to simulate: >>>> # sleep 2 >>>> File.open(pid_file, File::EXCL | File::WRONLY | File::CREAT) {|io| >>>> io.write($$)} >>>> trap(0) {File.delete pid_file} >>>> >>>> puts "OK, here we go." >>> Let me a question: is the above a fragment of a Linux init script written >>> in Ruby (rather than bash/sh as usual)? >> That was hacked together for demonstration purposes. It was not >> intended as an init script but rather as the demon itself - albeit >> without all the demonization stuff (detaching from terminal etc.) >> because I wanted to focus on the aspect of pid file handling and killing. > > Ok ok, I just asked as curiosity because some time ago I tryed to do a init > script in Ruby and couldn't do it properly... not remember the reason right > now... One small thing just comes to mind: you can replace the "trap(0) {..." with "at_exit {...". This is probably a bit more rubyish. It also has the advantage that you can have multiple at_exit handlers while you can only have one trap: robert@fussel ~ $ ruby19 -e '2.times {|i| at_exit { puts "exiting #{i}..."} }' exiting 1... exiting 0... robert@fussel ~ $ ruby19 -e '2.times {|i| trap(0) { puts "exiting #{i}..."} }' exiting 1... robert@fussel ~ $ >>> If so, according to LSB specifications it should return 0 (success) in >>> case of "start" action when the daemon is already running. >> Well, if you write a start script for that "ruby demon" you would have >> to handle exit codes properly. > > Ok, so later the init script could get "1" and return "0" as LSB states. Exactly. > Thanks a lot again. You're welcome! Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/