Add graceful shutdown.

On SIGINT or SIGTERM, keep reading until we see '\n', processing lines,
and then exit.
Clean up the graceful shutdown code a little.