Module: Aw

Defined in:
lib/aw.rb,
lib/aw/fork.rb

Overview

Namespace for the Aw library.

Examples:

Computes ‘6 * 7` in a sub-process and returns `42` to the current process.

Aw.fork! { 6 * 7 } # => 42

Computes ‘6 * 7` in a sub-process and returns `true` to the current process if no exception is thrown.

Aw.fork? { 6 * 7 } # => true

Defined Under Namespace

Classes: Fork

Class Method Summary collapse

Class Method Details

.fork!(&block) ⇒ #object_id

Runs the block inside a sub-process, and returns the computed value.

Examples:

Computes ‘6 * 7` in a sub-process and returns `42` to the current process.

Aw.fork! { 6 * 7 } # => 42

Computes ‘nil + 1` in a sub-process and raises `NoMethodError` to the current process.

Aw.fork! { nil + 1 } # => raise NoMethodError (undefined method `+' for nil:NilClass)

Parameters:

  • block (Proc)

    The code to run in a sub-process.

Returns:

  • (#object_id)

    Returns the value that has been returned in the block.

Raises:

  • (Exception)

    Exceptions raised in a block of code are propagated.



25
26
27
28
# File 'lib/aw.rb', line 25

def self.fork!(&block)
  read, write = ::IO.pipe
  Fork.new(read, write).call(&block)
end

.fork?(&block) ⇒ Boolean

Runs the block inside a sub-process, and returns ‘true` if no exception is thrown. Otherwise when an exception is raised, `false` is returned.

Examples:

Computes ‘6 * 7` in a sub-process and returns `true` to the current process.

Aw.fork? { 6 * 7 } # => true

Computes ‘nil + 1` in a sub-process and returns `false` to the current process.

Aw.fork? { nil + 1 } # => false

Parameters:

  • block (Proc)

    The code to run in a sub-process.

Returns:

  • (Boolean)

    Returns ‘true` if stat is successful, `false` if not.



42
43
44
45
46
# File 'lib/aw.rb', line 42

def self.fork?(&block)
  pid = ::Process.fork(&block)
  _, status = ::Process.wait2(pid)
  status.success?
end