DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Search For Running Processes

10.05.2010
| 4181 views |
  • submit to reddit
        Search for all running processes using a regular expression pattern and return PIDs for all processes matching it ...

Quick version ... there is probably a better way to do this ...

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)
          (h[File.basename(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

Version which does some rudimentary cleaning-up of the process name:

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

Simple use-case:

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>

On the side note: consider using the "sys-proctable" gem for proper process information and accounting. Available at: http://rubyforge.org/projects/sysutils/ and http://raa.ruby-lang.org/project/sys-proctable/.