Proper shutdown protocol to prevent hanging