--- a/src/xterm.c
+++ b/src/xterm.c
@@ -10442,7 +10442,7 @@ xim_close_dpy (struct x_display_info *dp
 #ifdef HAVE_X11R6_XIM
       struct xim_inst_t *xim_inst = dpyinfo->xim_callback_data;
 
-      if (dpyinfo->display)
+      if (X_DISPLAY_CONNECTED (dpyinfo->display))
 	{
 	  Bool ret = XUnregisterIMInstantiateCallback
 	    (dpyinfo->display, dpyinfo->rdb, xim_inst->resource_name,
@@ -10453,7 +10453,7 @@ xim_close_dpy (struct x_display_info *dp
       xfree (xim_inst->resource_name);
       xfree (xim_inst);
 #endif /* HAVE_X11R6_XIM */
-      if (dpyinfo->display)
+      if (X_DISPLAY_CONNECTED (dpyinfo->display))
 	XCloseIM (dpyinfo->xim);
       dpyinfo->xim = NULL;
       XFree (dpyinfo->xim_styles);
@@ -12056,7 +12056,7 @@ x_free_frame_resources (struct frame *f)
 
   /* If a display connection is dead, don't try sending more
      commands to the X server.  */
-  if (dpyinfo->display)
+  if (X_DISPLAY_CONNECTED (dpyinfo->display))
     {
       /* Always exit with visible pointer to avoid weird issue
 	 with Xfixes (Bug#17609).  */
@@ -12216,7 +12216,7 @@ x_destroy_window (struct frame *f)
 
   /* If a display connection is dead, don't try sending more
      commands to the X server.  */
-  if (dpyinfo->display != 0)
+  if (X_DISPLAY_CONNECTED (dpyinfo->display))
     x_free_frame_resources (f);
 
   dpyinfo->reference_count--;
@@ -13412,7 +13412,7 @@ x_delete_terminal (struct terminal *term
 #endif
 
   /* Normally, the display is available...  */
-  if (dpyinfo->display)
+  if (X_DISPLAY_CONNECTED (dpyinfo->display))
     {
       image_destroy_all_bitmaps (dpyinfo);
       XSetCloseDownMode (dpyinfo->display, DestroyAll);
--- a/src/xterm.h
+++ b/src/xterm.h
@@ -23,6 +23,9 @@ along with GNU Emacs.  If not, see <http
 #include <X11/Xlib.h>
 #include <X11/cursorfont.h>
 
+/* Xlib's "internal" header; we need this for the definition of XlibDisplayIOError. */
+#include <X11/Xlibint.h>
+
 /* Include Xutil.h after keysym.h to work around a bug that prevents
    correct recognition of AltGr key in some X versions.  */
 
@@ -850,6 +853,8 @@ extern void x_mark_frame_dirty (struct f
 #define FRAME_XIC_STYLE(f) ((f)->output_data.x->xic_style)
 #define FRAME_XIC_FONTSET(f) ((f)->output_data.x->xic_xfs)
 
+#define X_DISPLAY_CONNECTED(display) ((display != NULL) && !(display->flags & XlibDisplayIOError))
+
 /* X-specific scroll bar stuff.  */
 
 /* We represent scroll bars as lisp vectors.  This allows us to place
