hmm ... suddenly I like this new function; evading duplication :-)
I note, however, that the lines preceding each deleted close(fd); violate our coding standards; conditionals without braces round their dependent statements.  (Pre-existing)