Sha256: a42db6554eb845a00ffa91e7db7d645d6f54b2f4dc059380d25290c7d2a99dc9

Contents?: true

Size: 1.66 KB

Versions: 13

Compression:

Stored size: 1.66 KB

Contents

module Loops
  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

      # Detach from the controlling terminal
      unless sess_id = Process.setsid
        raise Daemons.RuntimeException.new('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

      Dir.chdir(Loops.root) # Make sure we're in the working directory
      File.umask(0000) # Insure sensible umask

      return sess_id
    end
  end
end

Version data entries

13 entries across 13 versions & 2 rubygems

Version Path
loops-2.0.9 lib/loops/daemonize.rb
loops-2.0.8 lib/loops/daemonize.rb
loops-2.0.7 lib/loops/daemonize.rb
loops-2.0.6 lib/loops/daemonize.rb
loops-2.0.5 lib/loops/daemonize.rb
loops-2.0.4 lib/loops/daemonize.rb
loops-2.0.3 lib/loops/daemonize.rb
qik-loops-2.1.4 lib/loops/daemonize.rb
loops-2.0.2 lib/loops/daemonize.rb
qik-loops-2.1.3 lib/loops/daemonize.rb
qik-loops-2.1.0 lib/loops/daemonize.rb
loops-2.0.1 lib/loops/daemonize.rb
loops-2.0.0 lib/loops/daemonize.rb