加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在jRuby中使用’fork’生成进程的替代方法?

发布时间:2020-12-17 03:36:09 所属栏目:百科 来源:网络整理
导读:在MRI Ruby中,我可以这样做: 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 con
在MRI Ruby中,我可以这样做:

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

但是上面的代码不会在jRuby中运行,因为它不支持’fork’方法:

NotImplementedError: fork is not available on this platform

在jRuby中有没有替代解决方案?

谢谢.

解决方法

这是一个很好的问题,但遗憾的是我不相信JVM可以安全地为您提供您想要的内容,如果您想要的是启动一个与父进程共享状态的新进程.那是因为forking只复制当前运行的线程.例如,GC线程不会被复制.您不希望在没有GC的情况下运行JVM.

使用fork的唯一半安全方法是在之后立即执行.

Charles Nutter在他的blog上首先说你可以使用FFI来分叉和执行,但随后提供了一个警告:

The biggest problem with using fork+exec in this way is that you can’t
guarantee *nothing* happens between the fork call and the exec call.
If,for example,the JVM decides to GC or move memory around,you can
have a fatal crash at the JVM process level. Because of that,I don’t
recommend using fork + exec via FFI in JRuby,even though it’s pretty
cool.

我倾向于相信他的建议.

因此,fork和exec会带来一些风险,但保持分叉的JVM会遇到麻烦.

你应该认真考虑塞尔吉奥评论中提出的替代方案.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读