From 95a1e89061eeca989b5fbdfc4181853cc08ff6c1 Mon Sep 17 00:00:00 2001 From: schneems Date: Tue, 25 Aug 2020 12:05:43 -0500 Subject: [PATCH] [close #39] Supporting different PIDs on Mac Currently when you call `GetProcessMem.new` with a different pid value than the current process it calls `GetProcessMem::Darwin.resident_size this uses FFI to get data from the mach kernel about the current process. - https://github.com/schneems/get_process_mem/pull/32 - https://stackoverflow.com/questions/18389581/memory-used-by-a-process-under-mac-os-x/23379216#23379216 This PR adds a test to ensure that memory results from different processes is correctly reported. This PR addresses the different PID problem by checking if a different pid other than Process.pid is being passed in. If that's the case then we will fall back to determining memory based off of shelling out to `ps`. There was a performance concern over using `Process.pid` but it appears to be relatively fast. It is approximately the speed of allocating 3 string object. --- CHANGELOG.md | 4 ++++ lib/get_process_mem.rb | 2 +- test/get_process_mem_test.rb | 11 ++++++++++- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 02e9f6d..3dc7c82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ## Master - unreleased +## 0.2.6 + +- Support returning memory from different PIDs on mac (https://github.com/schneems/get_process_mem/pull/41) + ## 0.2.5 - Use new sys-proctable interface (https://github.com/schneems/get_process_mem/pull/36) diff --git a/lib/get_process_mem.rb b/lib/get_process_mem.rb index e781209..9af2f5e 100644 --- a/lib/get_process_mem.rb +++ b/lib/get_process_mem.rb @@ -58,7 +58,7 @@ def linux? def bytes memory = linux_status_memory if linux? - memory ||= darwin_memory if RUNS_ON_DARWIN + memory ||= darwin_memory if RUNS_ON_DARWIN && Process.pid == pid memory ||= ps_memory end diff --git a/test/get_process_mem_test.rb b/test/get_process_mem_test.rb index 8f39297..f7b831f 100644 --- a/test/get_process_mem_test.rb +++ b/test/get_process_mem_test.rb @@ -1,11 +1,20 @@ require 'test_helper' class GetProcessMemTest < Test::Unit::TestCase - def setup @mem = GetProcessMem.new end + def test_different_pid_returns_different_memory + pid = Process.spawn("tail -f Gemfile") + + other_mem = GetProcessMem.new(pid) + assert @mem.kb > other_mem.kb + ensure + Process.kill('TERM', pid) if pid + Process.wait(pid) if pid + end + def test_seems_to_work assert @mem.kb > 0 assert @mem.mb > 0