开发者

How do I determine whether ruby can fork without excessive use of regexp?

开发者 https://www.devze.com 2022-12-28 10:53 出处:网络
Is it possible to determine whether the implementati开发者_运维问答on of ruby you\'re running on is capable of supporting fork, without running a regex against RUBY_PLATFORM that\'ll expand until it s

Is it possible to determine whether the implementati开发者_运维问答on of ruby you're running on is capable of supporting fork, without running a regex against RUBY_PLATFORM that'll expand until it summons Cthulhu?

(Related question: Ruby - How can I find out on which system my program is running?)

Edit: I tried Marc-Andre's suggestion. It doesn't work for jruby with fork disabled by default:

192-168-1-7:~ agrimm$ jruby --1.9 -S jirb 
irb(main):001:0> RUBY_VERSION
=> "1.9.2dev"
irb(main):002:0> Process.respond_to?(:fork)
=> true
irb(main):003:0> Process.fork
NotImplementedError: fork is unsafe and disabled by default on JRuby

Update: From Marc-Andre's link, it seems wiser heads than I have grappled with this problem from the perspective of creating ruby implementations, and failed.

From the perspective of someone who's writing a ruby library, what would be the most comprehensive incantation, short of running fork and seeing if it raises an exception?


In Ruby 1.9:

Process.respond_to?(:fork)  # => true if fork is supported, false otherwise

For Ruby 1.8, or JRuby (which doesn't implement this currently) you'll have to actually test it.

See also this long discussion on ruby-core.


Instead of error-prone testing against RUBY_PLATFORM or other things you could test fork itself:

def can_fork?
  pid = fork
  exit unless pid # exit the child immediately
  true
rescue NotImplementedError
  false
end

One downside would be if fork is somehow emulated which could make this check expensive.


A recent commit to rails uses

Config::CONFIG['host_os'] !~ /mswin|mingw/)

to test whether it's not on Windows, and

RUBY_PLATFORM !~ /java/

to test whether it's not on JRuby. However, I know it's possible to enable fork as a command-line switch. I'd have to look into whether there's any way of telling whether it's been enabled.

I suspect macruby doesn't support, or strongly discourages, forking, and from the thread Marc-Andre refers to, you can test for it with

 RUBY_ENGINE != "macruby"

Now for all the other platforms out there... (work in progress, marking as community wiki, please feel free to edit)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号