Fun with file descriptors
Posted Jun 8, 2007 7:16 UTC (Fri) by
quotemstr (subscriber, #45331)
In reply to:
Fun with file descriptors by bronson
Parent article:
Fun with file descriptors
What about a thread-specific default set of FD flags?
Using something like this, we wouldn't need to modify any existing APIs.
/* Internal glibc function */
A: old_fd_flags = kernel_default_fd_flags(FD_CLOEXEC | FD_RANDFD);
B: event_fd = super_duper_event_polling_mechanism_fd();
C: kernel_default_fd_flags(old_fd_flags);
Since the state is thread-specific, we don't need to worry about cross-thread synchronization. It wouldn't be inherited across exec, fork or clone, since it's intended for purely local options. I can't think of a situation where one would want to create a new thread and atomically give it a default set of FD flags.
It's race-free as well. If a fork happens between A and B, nothing unusual happens; the child process doesn't inherit the thread setting flags. If a fork happens after B, event_fd is closed when the child exec()s.
It's adheres to POSIX as long as the application doesn't touch kernel_default_fd_flags itself, and as long as any libraries restore flags after they're done with them.
Why not add an FD_CLOFORK owhile we're at it? That's a lot closer to what you'd want for a piece of code that allocated an internal file descriptor. Granted, multithreaded programs shouldn't fork except to then exec.
(
Log in to post comments)