Browse files

Merge pull request #2 from tobert/master

Add getursage() and alarm()
  • Loading branch information...
2 parents b640c65 + 58bec69 commit 502501f335a417d9aeecb9d6d4a19187a6ca3cc5 @postmodern committed Apr 12, 2012
Showing with 50 additions and 2 deletions.
  1. +19 −2 lib/ffi/libc/libc.rb
  2. +25 −0 lib/ffi/libc/rusage.rb
  3. +6 −0 spec/libc_spec.rb
View
21 lib/ffi/libc/libc.rb
@@ -2,6 +2,7 @@
require 'ffi/libc/timeval'
require 'ffi/libc/timezone'
require 'ffi/libc/ifaddrs'
+require 'ffi/libc/rusage'
require 'ffi'
@@ -31,6 +32,7 @@ def self.raise_error(error=self.errno)
attach_function :geteuid, [], :uid_t
attach_function :getgid, [], :gid_t
attach_function :getegid, [], :gid_t
+ attach_function :alarm, [:uint], :uint
# stdlib.h
attach_function :calloc, [:size_t, :size_t], :buffer_inout
@@ -82,15 +84,15 @@ def self.raise_error(error=self.errno)
attach_function :strrchr, [:buffer_in, :int], :pointer
attach_function :strstr, [:buffer_in, :string], :pointer
attach_function :strerror, [:int], :string
-
+
begin
attach_variable :stdin, :pointer
attach_variable :stdout, :pointer
attach_variable :stderr, :pointer
rescue FFI::NotFoundError
# stdin, stdout, stderr are not available on OSX
end
-
+
attach_function :fopen, [:string, :string], :FILE
attach_function :fdopen, [:int, :string], :FILE
attach_function :freopen, [:string, :string, :FILE], :FILE
@@ -153,5 +155,20 @@ def self.each_ifaddrs
freeifaddrs(ptr.get_pointer(0))
end
+
+ # /usr/include/bits/resource.h on Linux
+ # /usr/include/sys/resource.h on Darwin
+ RUSAGE_SELF = 0
+ RUSAGE_CHILDREN = -1
+ RUSAGE_THREAD = 1 # Linux/glibc only
+
+ attach_function :sys_getrusage, :getrusage, [:int, :pointer], :int
+
+ def self.getrusage(who=RUSAGE_SELF)
+ ru = RUsage.new
+ ret = sys_getrusage(who, ru)
+ raise_error(ret) unless ret == 0
+ ru
+ end
end
end
View
25 lib/ffi/libc/rusage.rb
@@ -0,0 +1,25 @@
+require 'ffi/libc/types'
+require 'ffi/libc/timeval'
+
+module FFI
+ module LibC
+ class RUsage < FFI::Struct
+ layout :ru_utime, Timeval,
+ :ru_stime, Timeval,
+ :ru_maxrss, :long,
+ :ru_ixrss, :long,
+ :ru_idrss, :long,
+ :ru_isrss, :long,
+ :ru_minflt, :long,
+ :ru_majflt, :long,
+ :ru_nswap, :long,
+ :ru_inblock, :long,
+ :ru_oublock, :long,
+ :ru_msgsnd, :long,
+ :ru_msgrcv, :long,
+ :ru_nsignals, :long,
+ :ru_nvcsw, :long,
+ :ru_nivcsw, :long
+ end
+ end
+end
View
6 spec/libc_spec.rb
@@ -6,4 +6,10 @@
require 'ffi/libc/libc'
}.should_not raise_error(FFI::NotFoundError)
end
+
+ it "should be able to fetch its own memory usage" do
+ require 'ffi/libc'
+ ru = FFI::LibC.getrusage
+ ru[:ru_maxrss].should be > 4000
+ end
end

0 comments on commit 502501f

Please sign in to comment.