I encountered an issue where a new pid might be shorter than the previous pid. What happens is the lock file gets written with the new PID, but there are trailing digits from the previous one, so when you try to stop the application, it fails.
I fixed this by changing the code that writes the PID to pad up to PID_MAXLEN (which is defined as 10). That way, no matter how short the pid is, it will add trailing spaces up to PID_MAXLEN characters, and there won't be any digits leftover from the previous PID.