Fix memory leak due to registered signal handlers; refactoring