module Process
class << self
def search(pattern)
result = Dir['/proc/[0-9]*/cmdline'].inject({}) do |h, file|
if (process = File.read(file).split(/\000|\s+/).first)
process = File.basename(process).gsub(/\W/, '')
(h[process] ||= []).push(file.match(/\d+/)[0].to_i)
end
h
end.map { |k, v| v if k.match(pattern) }.compact.flatten
result if result.any?
end
end
end
irb(main):184:0> `ps x -o cmd | awk '{ print $1 }' | grep -i bash | wc -l`
=> "8\n"
irb(main):185:0> Process.search(/bash/).size
=> 8
irb(main):186:0> `ps x -o cmd | awk '{ print $1 }' | grep -i sh | wc -l`
=> "17\n"
irb(main):187:0> Process.search(/sh/).size
=> 17
irb(main):188:0>
Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/edTiEXl7sUE/12355