Fixed a race condition.

Also fixes a file descriptor leak.