Fixes for incorrect PIDs written into stale PID files

The main issues are that the file is not emptied out before writing back the PID in the case that the file is stale (ie unlocked).  The solution is to rewind and truncate the file so that only the new PID is written.

For specific details of the two cases see the individual commit messages for fbb5c3161521eba68953464130329ea8a0cbc15b and 6a2c5f951829fbdf1963accc467df495b82e59c9, and their specs.