Class: MySampler::ProcessCtl

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeProcessCtl

Returns a new instance of ProcessCtl.



8
9
10
11
12
# File 'lib/mysampler/processctl.rb', line 8

def initialize
  @pidfile = ""
  @daemonize = false
  @pid = nil
end

Instance Attribute Details

#daemonizeObject

Returns the value of attribute daemonize.



5
6
7
# File 'lib/mysampler/processctl.rb', line 5

def daemonize
  @daemonize
end

#pidfileObject

Returns the value of attribute pidfile.



5
6
7
# File 'lib/mysampler/processctl.rb', line 5

def pidfile
  @pidfile
end

Instance Method Details

#startObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/mysampler/processctl.rb', line 15

def start
  trap(:INT)     { stop }
  trap(:SIGTERM) { cleanup }

  size = get_running_pids.size
  if size > 0
    puts "Daemon is already running"
    return 1
  end

#    Daemonize.daemonize if @daemonize
  if @daemonize
    #http://stackoverflow.com/questions/1740308/create-a-daemon-with-double-fork-in-ruby
    raise 'First fork failed' if (pid = fork) == -1
    exit unless pid.nil?

    Process.setsid
    raise 'Second fork failed' if (pid = fork) == -1
    exit unless pid.nil?

    Dir.chdir '/'
    File.umask 0000
    STDIN.reopen '/dev/null'
    STDOUT.reopen '/dev/null', 'a'
    STDERR.reopen STDOUT
  end
  write_pid unless pidfile == ""
  yield
  return 0
end

#statusObject

returns the exit status (1 if not running, 0 if running)



61
62
63
64
65
# File 'lib/mysampler/processctl.rb', line 61

def status
  size = get_running_pids.size
  puts "#{File.basename $0} is #{"not " if size < 1}running."
  return (size > 0) ? 0 : 1
end

#stopObject



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/mysampler/processctl.rb', line 46

def stop
  # call user code if defined
  begin 
    yield 
  rescue
  end
  get_running_pids.each do |pid|
    puts "Killing pid #{pid}"
    Process.kill :SIGTERM, pid
    # can't do anything below here.  Process is dead
  end
  return 0
end