fix memleak and simplify fd