module Forkoff

Constants

STRATEGIES

Public Instance Methods

default() click to toggle source
# File lib/forkoff.rb, line 8
def default
  @default ||= { 'processes' => 2 }
end
file() click to toggle source
# File lib/forkoff.rb, line 16
def file 
  'file'
end
file_result(arg, &block) click to toggle source
# File lib/forkoff.rb, line 103
def file_result arg, &block
  tmpfile do |fd|
    pid = fork

    unless pid
      result =
        begin
          block.call(arg)
        rescue Object => e
          e
        end
      fd.write( Marshal.dump( result ) )
      exit!
    end

    Process.waitpid pid
    fd.rewind
    data = fd.read
    result = Marshal.load( data )
    return result
  end
end
hostname() click to toggle source
# File lib/forkoff.rb, line 32
def hostname
  require 'socket'
  @hostname ||= (Socket.gethostname rescue 'localhost.localdomain')
end
pid() click to toggle source
# File lib/forkoff.rb, line 20
def pid
  @pid ||= Process.pid
end
pipe() click to toggle source
# File lib/forkoff.rb, line 12
def pipe
  'pipe'
end
pipe_result(arg, &block) click to toggle source
# File lib/forkoff.rb, line 75
def pipe_result arg, &block
  r, w = IO.pipe
  pid = fork

  unless pid
    r.close
    result =
      begin
        block.call(arg)
      rescue Object => e
        e
      end
    w.write( Marshal.dump( result ) )
    w.close
    exit!
  end

  w.close
  data = ''
  while(( buf = r.read(8192) ))
    data << buf
  end
  result = Marshal.load( data )
  r.close
  Process.waitpid pid
  return result
end
ppid() click to toggle source
# File lib/forkoff.rb, line 24
def ppid
  @ppid ||= Process.ppid
end
tid() click to toggle source
# File lib/forkoff.rb, line 28
def tid
  Thread.current.object_id.abs
end
tmpdir() click to toggle source
# File lib/forkoff.rb, line 37
def tmpdir
  require 'tmpdir'
  @tmpdir ||= Dir.tmpdir
end
tmpdir=(tmpdir) click to toggle source
# File lib/forkoff.rb, line 42
def tmpdir= tmpdir
  @tmpdir = tmpdir.to_s
end
tmpfile(&block) click to toggle source
# File lib/forkoff.rb, line 46
def tmpfile &block
  basename = [hostname, pid, ppid, tid, rand].join('-') 
  tmp = File.join(tmpdir, basename)

  fd = nil
  flags = File::CREAT|File::EXCL|File::RDWR

  42.times do
    begin
      fd = open tmp, flags
      break
    rescue Object
      sleep rand
    end
  end
  raise Error, "could not create tmpfile" unless fd

  if block
    begin
      return block.call(fd)
    ensure
      fd.close unless fd.closed? rescue nil
      FileUtils.rm_rf tmp rescue nil
    end
  else
    return fd
  end
end
version() click to toggle source
# File lib/forkoff.rb, line 4
def version
  '1.2.0'
end