Bobochka
1/29/2016 - 10:54 AM

Play with "fork" in Ruby

Play with "fork" in Ruby

def print_free_memory
  mem = `free`.split("\n")[1].split(' ')[3]
  p "Free memory: #{mem}"
end 

hashes = []

print_free_memory

1_000_000.times do |i|
  hashes << ['42', 'asdf']
end

def show_memory_usage(whoami)
  pid = Process.pid

  mem = `pmap #{pid}`

  puts "Memory usage for #{whoami} pid: #{pid} is: #{mem.lines.to_a.last}"

  print_free_memory

  sleep #keep the process alive
end

puts "Now lets fork this process and see what memory is allocated to the child"

puts "Before..."

print_free_memory

if fork
        show_memory_usage("parent")
else

        puts "After..."

        # 1000.times do |i|
        #   hashes[i * 2] = 'asdf'
        # end

        10.times { GC.start }

        show_memory_usage("child")
end