使用Ruby和FFI获得PID

时间:2021-09-27 17:02:29

I'm currently trying to determine the name of a parent process that launched a Ruby script. I might be very wrong (and don't hesitate in that case to point me to a simpler way of doing things), but I understand that the only way to do that is to rely on the FFI library.

我目前正在尝试确定启动Ruby脚本的父进程的名称。我可能是非常错的(并且在这种情况下不要犹豫,指出一种更简单的做事方式),但我知道唯一的方法是依靠FFI库。

So, I've installed the necessary packages (I'm on Ubuntu 10.10, so I ran sudo apt-get install libffi-*, which installs among other things libffi-ruby1.8 and libffi-dev), then I pasted the example available here into irb1.8, which failed as you can see below:

所以,我已经安装了必要的软件包(我在Ubuntu 10.10上,所以我运行了sudo apt-get install libffi- *,其中包括libffi-ruby1.8和libffi-dev等),然后我粘贴了这个例子可以在这里找到irb1.8,它失败了,你可以在下面看到:

$ irb
irb(main):001:0> require 'ffi'
=> true
irb(main):002:0> 
irb(main):003:0* module GetPid
irb(main):004:1>   extend FFI::Library
irb(main):005:1> 
irb(main):006:1*   attach_function :getpid, [], :uint
irb(main):007:1> end
LoadError: no library specified
        from /usr/lib/ruby/1.8/ffi/library.rb:79:in `ffi_libraries'
        from /usr/lib/ruby/1.8/ffi/library.rb:106:in `attach_function'
        from (irb):6
        from /usr/lib/ruby/1.8/ffi/memorypointer.rb:33
irb(main):008:0>
irb(main):009:0* puts GetPid.getpid
NoMethodError: undefined method `getpid' for GetPid:Module
     from (irb):9
        from /usr/lib/ruby/1.8/ffi/memorypointer.rb:33
irb(main):010:0>

Does anyone have a clue what I'm doing wrong?

有谁知道我做错了什么?

1 个解决方案

#1


3  

You now need to explicitly specify the library you want to import functions from.

您现在需要显式指定要从中导入函数的库。

e.g. (untested, but should be close)

require 'ffi'
module LibC
  extend FFI::Library

  ffi_lib 'c'  # ** this line is now needed **

  attach_function :getpid, [], :uint
end

There are more basic examples over at https://github.com/ffi/ffi/wiki/Basic-Usage

https://github.com/ffi/ffi/wiki/Basic-Usage上有更多基本示例

Btw, you can just use Process.pid to get the current process's pid, or Process.ppid to get the pid of its parent - see http://ruby-doc.org/core/classes/Process.html

顺便说一下,你可以使用Process.pid来获取当前进程的pid,或者使用Process.ppid获取其父进程的pid - 请参阅http://ruby-doc.org/core/classes/Process.html

#1


3  

You now need to explicitly specify the library you want to import functions from.

您现在需要显式指定要从中导入函数的库。

e.g. (untested, but should be close)

require 'ffi'
module LibC
  extend FFI::Library

  ffi_lib 'c'  # ** this line is now needed **

  attach_function :getpid, [], :uint
end

There are more basic examples over at https://github.com/ffi/ffi/wiki/Basic-Usage

https://github.com/ffi/ffi/wiki/Basic-Usage上有更多基本示例

Btw, you can just use Process.pid to get the current process's pid, or Process.ppid to get the pid of its parent - see http://ruby-doc.org/core/classes/Process.html

顺便说一下,你可以使用Process.pid来获取当前进程的pid,或者使用Process.ppid获取其父进程的pid - 请参阅http://ruby-doc.org/core/classes/Process.html