Why not set cwd before you grab the lock ?
This would simplify bailing out; and I don't see that it needs to be inside the locked segment.