Porting from Bitcoin: "Several shutdown-related fixes"
https://github.com/bitcoin/bitcoin/pull/844