Close all file handles on SIGHUP (fixes #1768)

This was originally fixed in 803655b79ccb0403f47cfcd2cfa5a6ed66301cbc
but was broken later in 118b300fcad4e6ffb0178fc00cf9fe26075101a5.