call_as_daemon (Daemonize)

    # File lib/daemons/daemonize.rb, line 142
      def call_as_daemon(block, logfile_name = nil, app_name = nil)
        rd, wr = IO.pipe

        if tmppid = safefork
          # parent
          wr.close
          pid = rd.read.to_i
          rd.close

          Process.waitpid(tmppid)

          return pid
        else
          # child

          rd.close

          # 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
          #if oldmode.zero?
            trap 'SIGHUP', 'IGNORE'
            exit if pid = safefork
          #end

          wr.write Process.pid
          wr.close

          $0 = app_name if app_name

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

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

          # Free file descriptors and
          # point them somewhere sensible
          # STDOUT/STDERR should go to a logfile

          STDIN.reopen "/dev/null" rescue nil

          if logfile_name
            begin
              STDOUT.reopen logfile_name, "a"
            rescue ::Exception
              STDOUT.reopen "/dev/null" rescue nil
            end
          else
            STDOUT.reopen "/dev/null" rescue nil
          end

          STDERR.reopen STDOUT rescue nil

          block.call

          exit
        end
      end