Proof of Concept: Allow to prevent fork from happening in known fork unsafe API

[Feature #20590]

For better of for worse, fork(2) remain the primary provider of
parallelism in Ruby programs. Even though it's frowned uppon in
many circles, and a lot of literature will simply state that only
async-signal safe APIs are safe to use after `fork()`, in practice
most APIs work well as long as you are careful about not forking
while another thread is holding a pthread mutex.

One of the APIs that is known cause fork safety issues is `getaddrinfo`.
If you fork while another thread is inside `getaddrinfo`, a mutex
may be left locked in the child, with no way to unlock it.

I think we could reduce the impact of these problem by preventing
in for the most notorious and common cases, by locking around
`fork(2)` and known unsafe APIs with a read-write lock.
This commit is contained in:
Jean Boussier 2024-05-29 16:46:04 +02:00
parent 2e5680d304
commit 63cbe3f6ac
Notes: git 2024-09-05 09:44:04 +00:00
6 changed files with 82 additions and 2 deletions

View file

@ -4227,12 +4227,17 @@ rb_fork_ruby(int *status)
prefork();
before_fork_ruby();
rb_thread_acquire_fork_lock();
disable_child_handler_before_fork(&old);
child.pid = pid = rb_fork();
child.error = err = errno;
disable_child_handler_fork_parent(&old); /* yes, bad name */
rb_thread_release_fork_lock();
if (pid == 0) {
rb_thread_reset_fork_lock();
}
after_fork_ruby(pid);
/* repeat while fork failed but retryable */