Brush up switch.c for error consistency.

Set errno and return non-zero value in case of error. Also release the lock
before returning from functions working with the shared segment.