python-trio / python-trio/trio
Better handling of os.fork from inside trio
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 7.3k
- Forks
- 431
- Avg merge
- 2d 17h
- Merged PRs (30d)
- 6
Description
If you call os.fork from inside a trio context, and then try to use trio in both the parent and the child, you are going to have a bad time. fork is a very powerful tool, and leaves the process in a strange state: the child is just like the parent, except that threads etc. have disappeared, and they share all fd's (including the self-pipe), etc. This seems essentially unsolvable: if you want to start a new process from trio using fork+exec, that's fine, but anything else is probably not going to work. I guess if you fork and then only execute synchronous code in the child then things might be mostly OK (though you've just leaked a bunch of memory in the child, because it will forever keep copies of all the parent process's data, and copy-on-write won't save you because of Python's well-known issues with GC causing un-sharing).
(See also bpo-21998, which is asyncio's version of this issue.)
We should at least document this. It would also be good to actually catch it and provide some error, since nobody reads the documentation.
One approach is to record the pid when we enter trio, and then each time we touch trio state, verify that os.getpid() still gives the same value. I guess "enter trio" here means any of the @_public methods in trio/_core, yielding to the event loop, and TrioToken.run_sync_soon?
In 3.7 there's os.register_at_fork, which could potentially be useful (maybe to reduce overhead?), but I'm not entirely sure how.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading the Trio entry points mentioned in trio/_core, including @_public methods, event-loop yielding, and TrioToken.run_sync_soon, alongside Python's os.register_at_fork. Determine whether the intended outcome is documentation, PID checks, or both; done should clearly prevent or explain unsafe Trio use after os.fork.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- operating-systems
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100