Yes, but unlike dup2.c where we are emulating fcntl(n, F_DUPFD, 3), you
are now introducing an arbitrarily large target

Actually, the same happens in dup2.c; the code I referred to is the one emulating dup2 using dup. You are confusing with your own popen-safer.c, which indeed has a very low bounded recursion.

such that your recursion
could now risk overflowing the stack.  We'd probably have to rewrite it to
track dup allocation attempts using a heap struct if target is larger than
some minimum (or, is mingw subject to a compile-time maximum of open fds
where we can just return EMFILE up front?).

The maximum valid file descriptor number for MSVCRT (and hence mingw) is 2047:

#include <errno.h>

int main()
{
  int i;
  for (i = 3; i < 4096; i++)
    if (dup2 (0, i) == -1)
      {
        printf ("%d %s\n", i, strerror (errno));
        exit (0);
      }
    else
      close (i);
}

and above the limit dup2 fails with EBADF. I didn't find any documentation but the limit is already quite high and so it is unlikely to increase: for Linux, the limit is 1024 (and it also fails with EBADF).

You can compute this at configure time and use a bitmask too, but I think it is overkill.

Paolo


Reply via email to