Module: Simple::Spawn

Extended by:
Spawn
Included in:
Spawn
Defined in:
lib/simple/spawn.rb

Instance Method Summary collapse

Instance Method Details

#pipeify(line) ⇒ Object



34
35
36
# File 'lib/simple/spawn.rb', line 34

def pipeify(line)
  line.scan( /([^"'|]+)|["']([^"']+)["']/ ).flatten.compact
end

#spawn(cmd) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/simple/spawn.rb', line 7

def spawn cmd
  commands = pipeify(cmd)

  tmp_in = $stdin
  tmp_out = $stdout
  pipe = []

  commands.each_with_index do |command, index|
    program, *args = Shellwords.shellsplit(command)

    if index+1 < commands.size
      pipe = IO.pipe
      tmp_out = pipe.last
    else
      tmp_out = $stdout
    end

    spawn_program(program, *args, tmp_out, tmp_in)

    tmp_out.close unless tmp_out == $stdout
    tmp_in.close unless tmp_in == $stdin
    tmp_in = pipe.first
  end

  Process.waitall
end

#spawn_program(program, *args, tmp_out, tmp_in) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/simple/spawn.rb', line 38

def spawn_program(program, *args, tmp_out, tmp_in)
  fork {
    unless tmp_out == $stdout
      $stdout.reopen(tmp_out)
      tmp_out.close
    end

    unless tmp_in == $stdin
      $stdin.reopen(tmp_in)
      tmp_in.close
    end

    exec program, *args
  }
end