Skip to content

util: manage SpawnProcess socket descriptors with RAII - #395

Open
javierpmateos wants to merge 1 commit into
bitcoin-core:masterfrom
javierpmateos:raii-socket-fds
Open

javierpmateos wants to merge 1 commit into
bitcoin-core:masterfrom
javierpmateos:raii-socket-fds

Conversation

@javierpmateos

Copy link
Copy Markdown
Contributor

Follow-up to #394, based on ryanofsky's suggestion to use kj::AutoCloseFd instead of handling descriptor cleanup manually.

SpawnProcess() could leak file descriptors if the second SocketPair(), connect_info_to_args, or MakeArgv() threw an exception.

This change wraps the descriptors in kj::AutoCloseFd as soon as they're created, releasing them when they're explicitly closed or handed off. It also uses RAII in the SocketPair() fallback for platforms without SOCK_CLOEXEC. The existing close error handling and child behavior are preserved.

Testing:

  • Added a test that throws from connect_info_to_args and checks that the socket is closed. It fails on master and passes with this change.
  • All 30 mptest cases pass, both normally and with SOCK_CLOEXEC disabled.
  • Checked with strace: when the callback throws, all four descriptors are closed with this change, while master leaves them open.

There are two minor differences: the fallback's fcntl error now includes the full expression, and on error paths two descriptors are closed after killing the child rather than before. Neither changes the intended behavior.

This doesn't address unexpected exceptions after fork() that could leave the child running. ReadSpawnResult() can't throw today, so this is only theoretical.

I used an AI coding assistant for the implementation. I reviewed the diff and ran the tests myself.

SpawnProcess could leak file descriptors if the second SocketPair(),
connect_info_to_args, or MakeArgv threw an exception.

Use kj::AutoCloseFd to take ownership of the descriptors as soon as
they're created. Release them when closing or returning them, keeping
the existing error handling and child behavior unchanged. Do the same
in the SocketPair() fallback path used when SOCK_CLOEXEC is not
available.

Add a test that throws from the callback and checks that its socket is
closed.
@DrahtBot

DrahtBot commented Nov 14, 2026 •

Copy link
Copy Markdown

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Reviews

See the guideline and AI policy for information on the review process.
A summary of reviews will appear here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants