Improved the _exit_cleanup() function to handle potential recursions