Skip to content

Commit

Permalink
[close #39] Supporting different PIDs on Mac
Browse files Browse the repository at this point in the history
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.

- #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.
  • Loading branch information
schneems committed Aug 25, 2020
1 parent abc7860 commit 95a1e89
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
4 changes: 4 additions & 0 deletions 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)
Expand Down
2 changes: 1 addition & 1 deletion lib/get_process_mem.rb
Expand Up @@ -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

Expand Down
11 changes: 10 additions & 1 deletion 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
Expand Down

0 comments on commit 95a1e89

Please sign in to comment.