Sha256: e33c846272eb5059e7d47f3ea960e2a8567dcbd27ce2befdd8ee18043bf785e7

Contents?: true

Size: 1.09 KB

Versions: 1

Compression:

Stored size: 1.09 KB

Contents

# frozen_string_literal: true

module Aw
  # The Fork class.
  class Fork
    # Initialize the class.
    #
    # @param read  [IO] The read endpoint.
    # @param write [IO] The write endpoint.
    def initialize(read, write)
      # Currently, not available on all platforms.
      raise 'fork() unimplemented' unless Process.respond_to?(:fork)

      @read   = read
      @write  = write
    end

    # @!attribute [r] read
    #
    # @return [IO] The read endpoint.
    attr_reader :read

    # @!attribute [r] write
    #
    # @return [IO] The write endpoint.
    attr_reader :write

    # Run the block inside a subprocess, and return the value.
    #
    # @return [#object_id] The result.
    def call(*, **, &block)
      pid = fork_and_return_pid(&block)
      write.close
      result = read.read
      Process.wait(pid)

      # rubocop:disable MarshalLoad
      Marshal.load(result)
      # rubocop:enable MarshalLoad
    end

    private

    def fork_and_return_pid
      fork do
        read.close
        result = yield
        Marshal.dump(result, write)
        exit!(0)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
aw-0.1.6 lib/aw/fork.rb