Sha256: c99cb769222cfd67f37ec807e957d3083a8abc238f84c076e112b58e1711036d

Contents?: true

Size: 1.39 KB

Versions: 1

Compression:

Stored size: 1.39 KB

Contents

# frozen_string_literal: true

require 'English'

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 ::NotImplementedError, 'fork()' 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 Security/MarshalLoad
      ::Marshal.load(result).tap do |r|
        raise r if r.is_a?(::Exception)
      end
      # rubocop:enable Security/MarshalLoad
    end

    private

    def fork_and_return_pid
      fork do
        read.close

        # rubocop:disable Lint/RescueException
        begin
          result = yield
        rescue ::Exception
          result = $ERROR_INFO
        end
        # rubocop:enable Lint/RescueException

        ::Marshal.dump(result, write)
        exit!(true)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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