Permalink
Browse files

Add some examples of MVM and FFI APIs.

git-svn-id: http://svn.codehaus.org/jruby/trunk/jruby@7317 961051c9-f516-0410-bf72-c9f7e237a7b7
  • Loading branch information...
1 parent 364c9ff commit c78f601e6d2a45570af149dc8153d2dd1a1cf00f @headius headius committed Jul 29, 2008
Showing with 64 additions and 0 deletions.
  1. +11 −0 samples/ffi.rb
  2. +28 −0 samples/mvm.rb
  3. +25 −0 samples/mvm_subvm.rb
View
11 samples/ffi.rb
@@ -0,0 +1,11 @@
+require 'ffi'
+
+module POSIX
+ # this line isn't really necessary since libc is always linked into JVM
+ set_ffi_lib 'c'
+
+ attach_function :getuid, :getuid, [], :uint
+ attach_function :getpid, :getpid, [], :uint
+end
+
+puts "Process #{POSIX.getpid} running as user #{POSIX.getuid}"
View
28 samples/mvm.rb
@@ -0,0 +1,28 @@
+require 'jruby/vm'
+
+# create the VMs
+vm1 = JRuby::VM.spawn(['-e' "load 'samples/mvm_subvm.rb'"])
+vm2 = JRuby::VM.spawn(['-e' "load 'samples/mvm_subvm.rb'"])
+
+# connect them to parent
+vm1 << JRuby::VM_ID
+vm2 << JRuby::VM_ID
+
+# connect them together
+vm1 << vm2.id
+vm2 << vm1.id
+
+# start them running
+vm1 << 1
+
+# let them run for a while, reading their progress
+run = true
+Thread.new { while run; puts JRuby::VM.get_message; end }
+sleep 20
+
+# shut them down
+run = false
+vm1 << 'done'
+vm2 << 'done'
+vm1.join
+vm2.join
View
25 samples/mvm_subvm.rb
@@ -0,0 +1,25 @@
+require 'jruby/vm'
+
+VM = JRuby::VM
+ID = JRuby::VM_ID
+
+# get the VM id of the parent
+parent = VM.get_message
+
+# get the VM id we're sending to
+other = VM.get_message
+
+VM.send_message(parent,
+ "VM #{ID} starting up, sibling is: #{other}, parent is: #{parent}")
+
+# loop until we receive nil, adding one and sending on
+while message = VM.get_message
+ break if message == "done"
+ sleep 0.5
+ new_message = message + 1
+ VM.send_message(parent,
+ "VM #{JRuby::VM_ID} received: #{message}, sending #{new_message}")
+ VM.send_message(other, message + 1)
+end
+VM.send_message(parent,
+ "VM #{JRuby::VM_ID} terminating")

0 comments on commit c78f601

Please sign in to comment.