Avoid deadlocks and error messages when exiting

This is pretty intrusive because for all our binaries (not only serverd) I now register CloseAllDBExit() which keeps all mutexes locked before returning. However I've tried to make sure it will be the last exit handler to run, so it should be OK.

I'm stress testing this for half an hour now and it shows no problems. More info by tomorrow.