On macOS we do not close the file descriptors, and instead mark them all as close-on-exec. So checking whether they are not valid does not work.
If the system has configured a lower limit (either soft or hard) on the number of open file descriptors, the test will fail. Make sure to check whether we have exceeded that limit and adapt the max number of file descriptors appropriately.
Warned-by: gcc