TS-1475: Fixed closing the fd and returning the correct value. Coverity #1021837