Over a million developers have joined DZone.

Search For Running Processes

·
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/.
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}