Sha256: 2d7f6bec1f7739cf6708c62ed96abdb309f8c3b7f6376e2f46c18ce85da671d4

Contents?: true

Size: 1.67 KB

Versions: 43

Compression:

Stored size: 1.67 KB

Contents

module Daemonizer
  module Daemonize
    def self.read_pid(pid_file)
      File.open(pid_file) do |f|
        f.gets.to_i
      end
    rescue Errno::ENOENT
      0
    end

    def self.check_pid(pid_file)
      pid = read_pid(pid_file)
      return false if pid.zero?
      if defined?(::JRuby)
        system "kill -0 #{pid} &> /dev/null"
        return $? == 0
      else
        Process.kill(0, pid)
      end
      true
    rescue Errno::ESRCH, Errno::ECHILD, Errno::EPERM
      false
    end

    def self.create_pid(pid_file)
      if File.exist?(pid_file)
        puts "Pid file #{pid_file} exists! Checking the process..."
        if check_pid(pid_file)
          puts "Can't create new pid file because another process is runnig!"
          return false
        end
        puts "Stale pid file! Removing..."
        File.delete(pid_file)
      end

      File.open(pid_file, 'w') do |f|
        f.puts(Process.pid)
      end

      return true
    end

    def self.daemonize(app_name)
      if defined?(::JRuby)
        puts "WARNING: daemonize method is not implemented for JRuby (yet), please consider using nohup."
        return
      end

      fork && exit # Fork and exit from the parent

      STDIN.reopen '/dev/null'
      STDOUT.reopen '/dev/null', 'a'
      STDERR.reopen STDOUT
      
      # Detach from the controlling terminal
      unless sess_id = Process.setsid
        raise 'cannot detach from controlling terminal'
      end

      # Prevent the possibility of acquiring a controlling terminal
      trap 'SIGHUP', 'IGNORE'
      exit if pid = fork

      $0 = app_name if app_name
      
      File.umask(0000) # Insure sensible umask

      return sess_id
    end
  end
end

Version data entries

43 entries across 43 versions & 1 rubygems

Version Path
daemonizer-0.5.0.beta.1 lib/daemonizer/daemonize.rb
daemonizer-0.4.18 lib/daemonizer/daemonize.rb
daemonizer-0.4.17 lib/daemonizer/daemonize.rb
daemonizer-0.4.16 lib/daemonizer/daemonize.rb
daemonizer-0.4.15 lib/daemonizer/daemonize.rb
daemonizer-0.4.14 lib/daemonizer/daemonize.rb
daemonizer-0.4.13 lib/daemonizer/daemonize.rb
daemonizer-0.4.12 lib/daemonizer/daemonize.rb
daemonizer-0.4.11 lib/daemonizer/daemonize.rb
daemonizer-0.4.10 lib/daemonizer/daemonize.rb
daemonizer-0.4.9 lib/daemonizer/daemonize.rb
daemonizer-0.4.8 lib/daemonizer/daemonize.rb
daemonizer-0.4.7 lib/daemonizer/daemonize.rb
daemonizer-0.4.6 lib/daemonizer/daemonize.rb
daemonizer-0.4.5 lib/daemonizer/daemonize.rb
daemonizer-0.4.4 lib/daemonizer/daemonize.rb
daemonizer-0.4.3 lib/daemonizer/daemonize.rb
daemonizer-0.4.2 lib/daemonizer/daemonize.rb
daemonizer-0.4.1 lib/daemonizer/daemonize.rb
daemonizer-0.4.0 lib/daemonizer/daemonize.rb