Add support to write pid to pidfile when running in daemon mode.
Move daemon related code to a separate file.
Remove pid file when exiting.
Support log redirection to a file.
Use line buffering on log files.
This makes sure the contents are written on the disk, so the user can
read the log.
Tiny cleanup for merge