+/*
+ * Exit gracefully, clearing the utmp entry and restoring tty attributes
+ * TODO: if debugging, this should free up any known resources if we can
+ */
+static XErrorHandler old_xerror_handler;
+
+static void
+rxvt_emergency_cleanup ()
+{
+ for (rxvt_term **t = rxvt_term::termlist.begin (); t < rxvt_term::termlist.end (); t++)
+ (*t)->emergency_cleanup ();
+}
+
+int
+rxvt_xerror_handler (Display *display, XErrorEvent *event)
+{
+ if (GET_R->allowedxerror == -1)
+ GET_R->allowedxerror = event->error_code;
+ else
+ {
+ //TODO: GET_R is most likely not the terminal which caused the error
+ //TODO: maybe just output the error and continue?
+ old_xerror_handler (display, event);
+ GET_R->destroy ();
+ }
+
+ return 0;
+}
+
+int
+rxvt_xioerror_handler (Display *display)
+{
+ rxvt_warn ("X connection to '%s' broken, unable to recover, exiting.\n",
+ DisplayString (display));
+ rxvt_emergency_cleanup ();
+ _exit (EXIT_FAILURE);
+}
+
+/*
+ * Catch a fatal signal and tidy up before quitting
+ */
+void
+rxvt_term::sig_term (sig_watcher &w)
+{
+#ifdef DEBUG_CMD
+ rxvt_warn ("caught signal %d, exiting.\n", w.signum);
+#endif
+ rxvt_emergency_cleanup ();
+ signal (w.signum, SIG_DFL);
+ kill (getpid (), w.signum);
+}
+
+/*----------------------------------------------------------------------*/