From: Ben Nagy Date: 2006-06-11T12:17:04+09:00 Subject: Re: Getting a list of Processes > -----Original Message----- > From: Daniel Berger [mailto:djberg96@gmail.com] > Sent: Sunday, June 11, 2006 5:26 AM > To: ruby-talk ML > Subject: Re: Getting a list of Processes > > ReggW wrote: > > Daniel Berger wrote: > >> ReggW wrote: > >>> How do you get a list of running Processes using Ruby? > >>> > >>> P.S. I'm on Windows > >>> > >>> Thanks > >>> > >> require 'sys/proctable' > >> include Sys > >> > >> ProcTable.ps{ |proc_struct| > >> p proc_struct [...] I don't know what you're trying to do, but here's some hackjob code to do it using Win32API. The basic method is to create a Toolhelp32 snapshot and then enumerate the processes using Process32First and Process32Next. --- require 'Win32API' # some constants TH32CS_SNAPPROCESS=0x00000002 Proc32Size=(9*4)+260 # 9 DWORDS plus a string of length MAX_PATH (default 260) class ProcessEntry32 attr_reader :size, :usage, :pid, :default_heap, :module_id, :threads, :parent_pid, :base_priority, :flags, :name def initialize( raw_entry ) @size=raw_entry[0..3].unpack('I').first @usage=raw_entry[4..7].unpack('I').first #MDSN: always zero @pid=raw_entry[8..11].unpack('I').first @default_heap=raw_entry[12..15].unpack('I').first # MSDN: always zero @module_id=raw_entry[16..19].unpack('I').first # MSDN: always zero @threads=raw_entry[20..23].unpack('I').first @parent_pid=raw_entry[24..27].unpack('I').first @base_priority=raw_entry[28..31].unpack('I').first @flags=raw_entry[32..35].unpack('I').first # MSDN: always zero @name=raw_entry[36..@size-1].split("\0").first end end CreateToolhelp32Snapshot=Win32API.new("kernel32","CreateToolhelp32Snapshot", 'LL','L') Process32First=Win32API.new("kernel32","Process32First",'LP','L') Process32Next=Win32API.new("kernel32","Process32Next",'LP','L') snaphandle=CreateToolhelp32Snapshot.Call(TH32CS_SNAPPROCESS,0) procentryraw="\0"*Proc32Size procentryraw[0..3]=int2raw(Proc32Size) # need to initialise size or Process32First will fail # int2raw is a little helper function I wrote when first learning, # to convert an int into a DWORD. The core is: # ("%.8x"%unsigned_int).scan(/../).reverse.map {|b| b.hex}.pack('cccc') # but there is bound to be a nicer way to do it, so don't copy it. ;) processes=[] if Process32First.Call(snaphandle,procentryraw) processes.push(ProcessEntry32.new(procentryraw)) else fail "horribly" end while Process32Next.call(snaphandle,procentryraw) == 1 processes.push(ProcessEntry32.new(procentryraw)) end processes.sort {|x,y| x.parent_pid <=> y.parent_pid}.each do |process| [do stuff] --- I'm sure that more experienced rubyists can correct my idiomatic usage. Win32API is scarcely documented, so maybe this will come in handy for someone at some point. Cheers, ben