tags:

views:

191

answers:

3

Is it possible to determine whether the implementation 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?

A: 

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.

gix
+2  A: 

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.

Marc-André Lafortune
Thanks for that link. Pointing to a definitive source to say "You can't do X" is very useful.
Andrew Grimm
A: 

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)

Andrew Grimm