Class: MiniProcess

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

Constant Summary collapse

DEFAULT_SLEEP =
0.2

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}, &block) ⇒ MiniProcess

options

:name         -
:sleep        - timeout between spawns
:log_file     -
:sync_log     - 
:working_dir  - for log
:after_fork


14
15
16
17
18
19
20
# File 'lib/mini_process.rb', line 14

def initialize(opts = {}, &block)
  @opts = opts
  @block = block
  @opts[:sync_log] ||= true

  raise "block should be" unless block
end

Instance Attribute Details

#pidObject

Returns the value of attribute pid.



2
3
4
# File 'lib/mini_process.rb', line 2

def pid
  @pid
end

Instance Method Details

#nameObject



52
53
54
# File 'lib/mini_process.rb', line 52

def name
  "#{@opts[:name]}[#{@pid}]"
end

#pauseObject



48
49
50
# File 'lib/mini_process.rb', line 48

def pause
  sleep (@opts[:sleep] || DEFAULT_SLEEP).to_f
end

#startObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/mini_process.rb', line 22

def start    
  GC.copy_on_write_friendly = true if GC.respond_to?(:copy_on_write_friendly=)

  @pid = fork do
    STDIN.reopen("/dev/null")
    log_name = @opts[:log_file] || "/dev/null"
    log_name = File.expand_path(log_name)
    STDOUT.reopen(log_name, "a")
    STDOUT.sync = @opts[:sync_log]
    STDERR.reopen(log_name, "a")
    STDERR.sync = @opts[:sync_log]
    @opts[:after_fork].call if @opts[:after_fork]
    @block.call
  end

  puts "start process #{name}"
  pause
  @pid
end

#stopObject



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

def stop
  return unless @pid
  Process.kill("KILL", @pid) rescue nil
  puts "stop #{name}"
end