Skip to content

Instantly share code, notes, and snippets.

@majioa
Created January 23, 2013 07:23
Show Gist options
  • Save majioa/4602831 to your computer and use it in GitHub Desktop.
Save majioa/4602831 to your computer and use it in GitHub Desktop.
Simple process monitor tool like `top` in ruby for linux.
#!/usr/bin/ruby
require 'thread'
require 'logger'
$KCODE = "utf-8"
class ProcMon < Logger::Application
def initialize()
super('ProcMon') # Name of the application.
end
def run
p = `ps aux`
c = 0
val = $0.gsub(/.*\//,"")
while p =~ /ruby.*#{val}/o
c = c + 1
p = p.sub(/#{val}/o, "")
end
if c > 1
@log.error("Duplex run")
exit
end
#loading list
l = IO.read('/usr/local/etc/procmon.conf')
mpl = []
l.each {|prg|
prg = prg.sub(/\n$/,'')
next if prg == ''
if prg =~ /.*\/+?(.*)/
name = $1
else
name = prg
end
mp = { 'found' => false,
'fullname' => prg,
'name' => name
}
mpl.push(mp)
}
while(true)
pl = `ps ax`
pl.each { |prc|
next if prc !~ /^\s*(\d+)\s+\S+\s+\S+\s+[\d:]+\s+(.*)\s+$/
name = $2
mpl.each {|mp|
if name =~ /#{mp['name']}/
mp['found'] = true
log(DEBUG, "The program #{mp['fullname']} has already run")
end
}
}
mpl.each {|mp|
unless mp['found']
log(INFO, "The #{mp['fullname']} program will be run")
pid = fork {`#{mp['fullname']} &`}
Process.detach(pid)
log(INFO, "Program has run")
end
mp['found'] = false
}
sleep 10
end
end
end
status = ProcMon.new().start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment