Alternative to spawning a process using "fork" in jRuby?

In MRI Ruby, I can do this:

def transfer
  internal_server = self.init_server
  pid = fork do
    internal_server.run
  end

  # Make the server process run independently.
  Process.detach(pid)

  internal_client = self.init_client
  # Do other stuff with connecting to internal_server...
  internal_client.post('some data')    
ensure
  # Kill server
  Process.kill('KILL', pid) if pid
end

However, the above code will not run in jRuby as it does not support the fork method:

NotImplementedError: fork is not available on this platform

Is there an alternative solution for this in jRuby?

Thank.

+5
source share
2 answers

I found a solution for this. We can use the built-in FFI library in JRuby to "simulate" Process.fork in the MRI.

# To mimic the Process.fork in MRI Ruby
module JRubyProcess
  require 'ffi'
  extend FFI::Library
  ffi_lib FFI::Library::LIBC
  attach_function :fork, [], :int
end

pid = JRubyProcess.fork do
  #internal_server.run
end

More details:

https://github.com/ffi/ffi

http://blog.headius.com/2008/10/ffi-for-ruby-now-available.html

+1
source

, , , , JVM , , , . , forking . , GC, , . JVM GC.

fork - exec.

, blog, , FFI fork exec, :

fork + exec , * fork exec. , , JVM GC , JVM. - fork + exec FFI JRuby, .

.

, fork exec , JVM .

, .

+7

All Articles