wait_and_kill function added and cleanup