fix issue with EMFILE and memleaks on failure