Class: Shellter::Runners::Background

Inherits:
Base
  • Object
show all
Defined in:
lib/shellter/runners/background.rb

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from Shellter::Runners::Base

Instance Method Details

#run(command) {|StringIO.new, StringIO.new, StringIO.new, reader.gets.strip.to_i| ... } ⇒ Object

Yields:

  • (StringIO.new, StringIO.new, StringIO.new, reader.gets.strip.to_i)


4
5
6
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
33
# File 'lib/shellter/runners/background.rb', line 4

def run(command, &block)
  ensure_forking!

  # io for child process
  reader, writer = IO.pipe 

  # first fork, create a session leader
  fork do
    reader.close
    Process.setsid 

    # second fork, create a detached child
    # and write its pid to the writer pipe
    result = fork do
      Dir.chdir "/" 
      STDIN.reopen "/dev/null" 
      STDOUT.reopen "/dev/null", "a" 
      STDERR.reopen "/dev/null", "a"

      exec command             
    end
    
    # write the pid of the forked child to the pipe
    writer.puts result
  end

  writer.close
  
  yield StringIO.new, StringIO.new, StringIO.new, reader.gets.strip.to_i
end