From: Amos Date: 2001-05-02T22:23:03+09:00 Subject: [ruby-talk:14541] Re: daemon ruby script >>>>> On Thu, 26 Apr 2001 19:10:09 +0900, >>>>> Patrik Sundberg (ps) writes: ps> I would like to have one of my ruby programs running in the background at all ps> times like a normal UNIX daemon (it is a daemon logging temperature data to a ps> database). I thought this would be a easy enough task since all the syscalls ps> is right there from the start. I somehow don't manage to get it right anyway.. ps> I tried do write something along the lines of the BSD call daemon(3): ps> -------------------------------------------------------------------------- ps> def daemon(doClose, doChdir) ps> if fork != nil ps> exit(0); ps> end ps> Process.setsid ps> if doChdir ps> Dir.chdir("/") ps> end ps> if doClose ps> $stdin.close ps> $stdout.close ps> $stderr.close ps> $stdin = $stdout = $stderr = open("/dev/null", "rw") ps> end ps> end ps> [ read some args etc ] ps> if fgFlag ps> main ps> else ps> print "Fork to background! \n" ps> daemon(true, true) ps> main ps> end ps> -------------------------------------------------------------------------- I've also been working on a daemon process, one I'm hoping to put on RAA before long. Here's what I did, and it seems to be working pretty well: ## ## Become a daemon! ## def go_daemon unless Process.uid == 0 $stderr.puts "#{$0} must be run as root!" exit! end Dir.chdir PrayConfig.wrkdr File.umask 077 trap "SIGCLD", "IGNORE" if $DEBUG $stderr.puts "DEBUG enabled, running in foreground" else ## close unneeded descriptors $stdin.close $stdout.close $stderr.close ## drop into the background. pid = fork if pid ## parent: save pid of child, then exit File.open(PrayConfig.pidfl, "w") do |file| file.puts pid end exit! end ## change process group and lose control tty Process.setpgrp end ## Run at higher priority so that runaways won't get away, but try ## not to directly compete with sched, pageout, and fsflush. Process.setpriority Process::PRIO_PROCESS, Process.pid, -10 ## Initialize syslog $thishost = Socket.gethostbyname(Socket.gethostname)[0] $sl = Syslog.new 'pray', Syslog::LOG_PID|Syslog::LOG_CONS, Syslog::LOG_DAEMON end ## ## "MAIN" ## go_daemon -- Amos