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_argsand checks that the socket is closed. It fails on master and passes with this change. - All 30
mptestcases pass, both normally and withSOCK_CLOEXECdisabled. - 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.