More resilient shutdown

This code handles shutdown better and prevents a nasty segmentation fault at the end