Fix issues with daemonising

This fixes a problem with a buffer that could end up padded with
garbage.

This also clarifies the code a bit and adds extra logging for errors
that could occur during daemonising.