Improve fd reallocation safety

The algorithm should now always be able to swap the files associated to
the original stdio file descriptors correctly.