Last active
May 11, 2016 13:02
-
-
Save komasaru/6620545 to your computer and use it in GitHub Desktop.
Ruby script testing to daemonize a ruby script.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#********************************************* | |
# デーモン化テスト | |
#********************************************* | |
# | |
class TestDaemon | |
def initialize | |
# 割り込みフラグ | |
@flag_int = false | |
# ファイル名 | |
@pid_file = "./test_daemon.pid" # PID ファイル | |
out_file = "./test_daemon.txt" # 出力ファイル | |
# 出力ファイル OPEN | |
@out_file = File.open(out_file, "w") | |
end | |
# 起動 | |
def run | |
begin | |
# 開始メッセージ | |
@out_file.puts "[START]" | |
# デーモン化 | |
daemonize | |
# トラップ(割り込み)設定 | |
set_trap | |
# 処理実行 | |
execute | |
# 終了メッセージ | |
@out_file.puts "[E N D]" | |
rescue => e | |
STDERR.puts "[ERROR][#{self.class.name}.run] #{e}" | |
exit 1 | |
end | |
end | |
private | |
# デーモン化 | |
def daemonize | |
begin | |
# デーモン化 | |
# ( RUBY_VERSION < 1.9 ) | |
# exit!(0) if Process.fork | |
# Process.setsid | |
# exit!(0) if Process.fork | |
# ( RUBY_VERSION >= 1.9 ) | |
Process.daemon(true, true) | |
# PID ファイル生成 | |
open(@pid_file, 'w') {|f| f << Process.pid} if @pid_file | |
rescue => e | |
STDERR.puts "[ERROR][#{self.class.name}.daemonize] #{e}" | |
exit 1 | |
end | |
end | |
# トラップ(割り込み)設定 | |
def set_trap | |
begin | |
Signal.trap(:INT) {@flag_int = true} # SIGINT 捕獲 | |
Signal.trap(:TERM) {@flag_int = true} # SIGTERM 捕獲 | |
rescue => e | |
STDERR.puts "[ERROR][#{self.class.name}.set_trap] #{e}" | |
exit 1 | |
end | |
end | |
# 処理実行 | |
def execute | |
begin | |
count = 0 | |
loop do | |
break if @flag_int | |
sleep 1 | |
@out_file.puts count += 1 | |
@out_file.flush | |
end | |
rescue => e | |
STDERR.puts "[ERROR][#{self.class.name}.execute] #{e}" | |
@out_file.close | |
exit 1 | |
end | |
end | |
end | |
obj_proc = TestDaemon.new | |
obj_proc.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment