tty_wait_background: improve locking.
(cherry picked from commit a008bdeda3b8278fe600cf83ecf44acd1ccb30b6)