Sha256: 24532f39d9a2ef87557ae5fad35457e991436ff989f1f5adfb0fa526cfee3811

Contents?: true

Size: 1.64 KB

Versions: 24

Compression:

Stored size: 1.64 KB

Contents

# Daemonize code provided by Travis Whitton
#
# http://grub.ath.cx/daemonize/
module Daemonize
  #VERSION = "0.1.2"

  # Try to fork if at all possible retrying every 5 sec if the
  # maximum process limit for the system has been reached
  def safefork
    tryagain = true

    while tryagain
      tryagain = false
      begin
        if pid = fork
          return pid
        end
      rescue Errno::EWOULDBLOCK
        sleep 5
        tryagain = true
      end
    end
  end

  # This method causes the current running process to become a daemon
  #
  # If closefd is true, all existing file descriptors are closed
  def daemonize(oldmode=0, closefd=false)
    srand # Split rand streams between spawning and daemonized process
    safefork and exit # Fork and exit from the parent

    # Detach from the controlling terminal
    unless sess_id = Process.setsid
      raise 'Cannot detach from controlled terminal'
    end

    # Prevent the possibility of acquiring a controlling terminal
    if oldmode.zero?
      trap 'SIGHUP', 'IGNORE'
      exit if pid = safefork
    end

    Dir.chdir "/"   # Release old working directory
    File.umask 0000 # Insure sensible umask

    if closefd
      # Make sure all file descriptors are closed
      ObjectSpace.each_object(IO) do |io|
        unless [STDIN, STDOUT, STDERR].include?(io)
          io.close rescue nil
        end
      end
    end

    STDIN.reopen "/dev/null"       # Free file descriptors and
    STDOUT.reopen "/dev/null", "a" # point them somewhere sensible
    STDERR.reopen STDOUT           # STDOUT/STDERR should go to a logfile
    return oldmode ? sess_id : 0   # Return value is mostly irrelevant
  end
end

Version data entries

24 entries across 24 versions & 1 rubygems

Version Path
airake-0.1.11 lib/airake/daemonize.rb
airake-0.1.12 lib/airake/daemonize.rb
airake-0.2.10 lib/airake/daemonize.rb
airake-0.2.1 lib/airake/daemonize.rb
airake-0.2.11 lib/airake/daemonize.rb
airake-0.2.13 lib/airake/daemonize.rb
airake-0.2.12 lib/airake/daemonize.rb
airake-0.2.3 lib/airake/daemonize.rb
airake-0.2.14 lib/airake/daemonize.rb
airake-0.2.2 lib/airake/daemonize.rb
airake-0.2.4 lib/airake/daemonize.rb
airake-0.2.5 lib/airake/daemonize.rb
airake-0.3.1 lib/airake/daemonize.rb
airake-0.3.2 lib/airake/daemonize.rb
airake-0.4.0 lib/airake/daemonize.rb
airake-0.2.6 lib/airake/daemonize.rb
airake-0.2.7 lib/airake/daemonize.rb
airake-0.2.8 lib/airake/daemonize.rb
airake-0.2.9 lib/airake/daemonize.rb
airake-0.4.1 lib/airake/daemonize.rb