Skip to content

Instantly share code, notes, and snippets.

@ik5
Created June 22, 2010 18:43
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save ik5/448884 to your computer and use it in GitHub Desktop.
Save ik5/448884 to your computer and use it in GitHub Desktop.
a quick and dirty jruby daemon based on basic_daemon
#!/usr/bin/env jruby
#
#
require 'rubygems'
require 'spoon'
EXEC = '/tmp/exec.rb'
PID_PATH = '/tmp/exec.pid'
WORK_PATH = '/tmp/'
def create_pid(pid)
begin
open(PID_PATH, 'w') do |f|
f.puts pid
end
rescue => e
STDERR.puts "Error: Unable to open #{PID_PATH} for writing:\n\t" +
"(#{e.class}) #{e.message}"
exit!
end
end
def get_pid
pid = false
begin
open(PID_PATH, 'r') do |f|
pid = f.readline
pid = pid.to_s.gsub(/[^0-9]/,'')
end
rescue => e
STDERR.puts "Error: Unable to open #{PID_PATH} for reading:\n\t" +
"(#{e.class}) #{e.message}"
end
pid.to_i
end
def remove_pidfile
begin
File.unlink(PID_PATH)
rescue => e
STDERR.puts "ERROR: Unable to unlink #{path}:\n\t" +
"(#{e.class}) #{e.message}"
exit
end
end
def process_exists?
begin
pid = get_pid
return false unless pid
Process.kill(0, pid)
true
rescue Errno::ESRCH, TypeError # "PID is NOT running or is zombied
false
rescue Errno::EPERM
STDERR.puts "No permission to query #{pid}!";
rescue => e
STDERR.puts "(#{e.class}) #{e.message}:\n\t" +
"Unable to determine status for #{pid}."
false
end
end
def stop
begin
pid = get_pid
STDERR.puts "pid : #{pid}"
while true do
Process.kill("TERM", pid)
Process.wait(pid)
sleep(0.1)
end
puts "here"
rescue Errno::ESRCH # no more process to kill
remove_pidfile
STDOUT.puts 'Stopped the process'
rescue => e
STDERR.puts "unable to terminate process: (#{e.class}) #{e.message}"
end
end
def start
#if process_exists?
# STDERR.puts "The process #{EXEC} already running. Restarting the process"
# stop
#end
pid = Spoon.spawnp EXEC, *ARGV
create_pid(pid)
Process.setsid
#at_exit do
# remove_pidfile
#end
Dir::chdir(WORK_PATH)
File::umask(0)
#STDIN.reopen("/dev/null", 'r')
#STDOUT.reopen("/dev/null", "w")
#STDERR.reopen("/dev/null", "w")
end
if ARGV[0] == 'start'
start
elsif ARGV[0] == 'stop'
stop
elsif ARGV[0] == 'restart'
stop
start
else
STDERR.puts "Usage: tts_main.rb <start|stop|restart>"
exit!
end
#!/usr/bin/env jruby
#
#
while true
puts 'in loop'
sleep 2.5
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment