[musl] Re: Tweaking the program name for <err.h> functions

Zack Weinberg zack at owlfolio.org
Tue Mar 12 14:21:19 UTC 2024


On Tue, Mar 12, 2024, at 9:54 AM, Florian Weimer wrote:
>> Doing this would break many programs, such as:
>> - most of coreutils, e.g. programs like ls, cat or head, since they
>>   always `close` their input and output descriptors (when they've
>>   written or read something) to make sure to diagnose all errors
>
> A slightly better way to do this is to do fflush (stdout) followed by
> error checking on close (dup (fileno (stdout))).

Does that actually report delayed write errors?  As you have it,
the close() just drops the fd created by the dup(), the OFD is
still referenced by fd 1 and therefore remains open.  I would
expect scrupulously correct and thread-safe code for detecting
write errors on stdout without fd 1 ever becoming invalid to
look something like this:

int stub_stdout = open("/dev/null", O_WRONLY|O_CLOEXEC);
if (stub_stdout < 0)
  perror_exit("/dev/null");

flockfile(stdout);
if (ferror(stdout) || fflush(stdout))
  perror_exit("stdout: write error");

int original_stdout = fcntl(fileno(stdout), F_DUPFD_CLOEXEC, 3);
if (original_stdout < 0)
  perror_exit("dup(stdout)");  // e.g. ENFILE

dup2(stub_stdout, fileno(stdout)); // failure here should be impossible
close(stub_stdout); // ditto

funlockfile(stdout);
if (close(original_stdout) < 0)
  perror_exit("stdout: write error");

... Which is enough of a pain in the neck that I can't blame people
for wanting to just do close(1), especially during process termination.

(I thought Linux had a "swap these two fds" mode for dup3(), which would
simplify the above a bunch and get rid of one of the two places where you
can hit the file descriptor limit, but it's not mentioned in my copy of
the manpage. Did I just dream it?)

zw


More information about the libbsd mailing list