Skip to content

Commit fe4ead7

Browse files
committed
Ruby 3.1: decorate Process._fork if available
Ref: https://bugs.ruby-lang.org/issues/17795 This new API makes it much easier to correctly intercept forks.
1 parent e5b814c commit fe4ead7

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

activesupport/lib/active_support/fork_tracker.rb

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,16 @@
22

33
module ActiveSupport
44
module ForkTracker # :nodoc:
5+
module ModernCoreExt
6+
def _fork
7+
pid = super
8+
if pid == 0
9+
ForkTracker.check!
10+
end
11+
pid
12+
end
13+
end
14+
515
module CoreExt
616
def fork(...)
717
if block_given?
@@ -28,14 +38,17 @@ module CoreExtPrivate
2838

2939
class << self
3040
def check!
31-
if @pid != Process.pid
41+
new_pid = Process.pid
42+
if @pid != new_pid
3243
@callbacks.each(&:call)
33-
@pid = Process.pid
44+
@pid = new_pid
3445
end
3546
end
3647

3748
def hook!
38-
if Process.respond_to?(:fork)
49+
if Process.respond_to?(:_fork) # Ruby 3.1+
50+
::Process.singleton_class.prepend(ModernCoreExt)
51+
elsif Process.respond_to?(:fork)
3952
::Object.prepend(CoreExtPrivate) if RUBY_VERSION < "3.0"
4053
::Kernel.prepend(CoreExtPrivate)
4154
::Kernel.singleton_class.prepend(CoreExt)

0 commit comments

Comments
 (0)