Class: XMP2Assert::Spawn

Inherits:
Object
  • Object
show all
Defined in:
lib/xmp2assert/spawn.rb

Overview

Helper class to spawn a ruby process, and communicate with it.

Instance Method Summary collapse

Constructor Details

#initialize(path, rubyopts: nil, **opts) {|pid, stdin, stdout, stderr, tx, rx| ... } ⇒ Spawn

Returns a new instance of Spawn.

Parameters:

  • path (#to_path)

    a path to a ruby program.

  • rubyopts (Array<String>) (defaults to: nil)

    extra opts to pass to ruby interpreter.

  • opts (Hash)

    extra opts to pass to Process.spawn

Yield Parameters:

  • pid (Integer)

    child process' pid.

  • stdin (IO)

    child process stdin.

  • stdout (IO)

    child process stdout.

  • stderr (IO)

    child process stderr.

  • tx (IO)

    pipe to communicate.

  • rx (IO)

    pipe to communicate.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/xmp2assert/spawn.rb', line 41

def initialize path, rubyopts: nil, **opts
  ours, theirs, spec = pipes i'r w w r w'
  opts.update Hash[spec]

  argv = [RbConfig.ruby, rubyopts, path.to_path]
  argv << theirs[3..4].map {|i| i.to_i.to_s }
  argv.flatten!
  argv.compact!

  begin
    pid = Process.spawn(*argv, opts)
    theirs.each(&:close)
    stdin, stdout, stdrrr, rx, tx = *ours
    yield pid, stdin, stdout, stdrrr, rx, tx
  ensure
    begin
      ours.each(&:close)
    rescue IOError
      # OK, nothing can be done by us for closed streams.
    ensure
      Process.waitpid pid if pid
    end
  end
end