tell if writing pid file failed

Check the close return value.  Disk could be full, and it is easy to miss
such with buffered file operations.

Signed-off-by: Sami Kerola <kerolasa@iki.fi>
remove potential race condition

Signed-off-by: Sami Kerola <kerolasa@iki.fi>
update state file always after initialization

Earlier code left old pid in place.

Signed-off-by: Sami Kerola <kerolasa@iki.fi>