If this can be called more than once in a single execution of the binary that results, you need to reset fd = -1; after close()ing it.