Re: O_CLOEXEC Lassi Kortela 26 Jul 2020 18:57 UTC

> In open-file entry, O_CLOEXEC is missing from flags.   I think it's added in POSIX.1-2008.
> It's useful to prevent fd leakage.

+1. Great to hear that it's now blessed by POSIX.

Would a procedure to set the flag for already opened fd's also make
sense? fcntl(fd, F_SETFD, old_flags | FD_CLOEXEC);

> I agree that's the right thing (closed on exec by default), but I wonder
> if that's a sufficient reason to hide a feature.  There can be a case
> that the foreign library fork()s and you want CLOEXEC (you also need
> fcntl to set CLOEXEC on Scheme ports backed with fd, but one at a time...)

> In ProcessesCowan things work the other way around: when you exec or
> spawn a new process, you are given a list of fds *not* to be closed,
> and everything else is closed except 0, 1, 2.

Starting from a blank slate, close-on-exec would probably be a better
default. But Unix was designed to keep fd's open by default and we are
stuck with it.

Working around this in Scheme is not as easy as it sounds.

A closefrom() system call is available in Solaris, NetBSD, OpenBSD,
FreeBSD, DragonFly BSD, and Minix. Notably absent from this list are
Linux and Haiku (the BeOS remake - BeOS implements a large and useful
part of POSIX). closefrom(n) closes all fds >= n.

Some libc people think closefrom() is a bad idea since a library may
require some fd's to be kept open across an exec boundary and closing
everything in bulk may cause problems for them. My memory is fuzzy, but
IIRC it's acceptable to implement parts of POSIX using fd's in this way.

Manually calling close() in a loop is slow and it's not clear how many
fd's to try.