Errno::ENOMEM 当进程 shell 在使用交换时退出

Errno::ENOMEM when process shell out while using swap

我有一个 ruby 脚本,它在内存中加载大量数据,然后需要 shell 出来对这些数据执行任务。但有时,数据太大以至于脚本在交换中 运行,在这种情况下,shelling out 给我一个 Errno::ENOMEM 错误。

这是重现问题的脚本:

def current_process_ram
  pid, size = `ps ax -o pid,rss | grep -E "^[[:space:]]*#{$$}"`.strip.split.map(&:to_i)
  size / 1000
end

def display_current_process_ram
  "Current RAM: #{current_process_ram}"
end

puts display_current_process_ram

array = []
one_gig = 14_000_000
0.upto(one_gig * 2.5) do
  array << '12345'
end
sleep 2
`ls`

puts display_current_process_ram

htop 在 运行 脚本之前:

htop 当脚本为 运行:

产生的错误:

deploy@vagrant-ubuntu-trusty-64:~/statusmachine$ ruby test.rb
Current RAM: 7
test.rb:19:in ``': Cannot allocate memory - ls (Errno::ENOMEM)
        from test.rb:19:in `<main>'

它在 Ubuntu 服务器 "trusty tahr" 虚拟机上运行。

我的问题

为什么我会收到 Errno::ENOMEM 错误?我希望系统调用能够工作,因为我有足够的交换空间来执行它。


编辑:如果我将脚本更改为仅使用 1 gig,它不会在 shell 退出时爆炸。

编辑 2:当我 shell 退出时,仍然有很多交换空间来执行系统调用,所以不应该发生 Errno::ENOMEM

编辑 3:澄清了我的问题。

Why do I get the Errno::ENOMEM error?

因为Ruby无法分配足够的内存。

当您使用典型的 Ruby、a.k.a 时,

Ruby 的内存消耗 gem 很难(恕我直言)。 KRI、MRI、YARV。

这篇文章可能对您有所帮助:

http://adamniedzielski.github.io/blog/2014/02/05/fighting-paperclip-errno-enomem-error/

文章的核心思想是:"To create the child process, free memory must be greater than the memory taken by the parent process."

文章中的解决方案是切换到使用 posix-spawn gem:

https://github.com/rtomayko/posix-spawn