XLib Disconnection Callback

315 Views Asked by At

I use XLib and XRand to get some information about the connected displays on an embedded system.

class Foo {
private:
    Display *_display{};

public:
    Foo() {
        _display = XOpenDisplay(":0.0");
    }

    void getSomeInfo() const {
        /* Get some info with _display */
    }

    ~Foo() {
        XCloseDisplay(_display);
    }
}

The problem is, X server can be shut down (for low power or some other purposes) after the creation of Foo instance and before calling getSomeInfo(), which causes immediate death of my application because XLib tries to exit application in case of errors.

Is there any mechanism, like a callback, which would allow me to understand that X Server went down and I should not use the _display pointer anymore ?

1

There are 1 best solutions below

2
On

I fear that your only option is to use XSetIOErrorHandler and then do something ugly.

From https://tronche.com/gui/x/xlib/event-handling/protocol-errors/XSetIOErrorHandler.html:

The XSetIOErrorHandler() sets the fatal I/O error handler. Xlib calls the program's supplied error handler if any sort of system call error occurs (for example, the connection to the server was lost). This is assumed to be a fatal condition, and the called routine should not return. If the I/O error handler does return, the client process exits.

The "do something ugly" that I would suggest is to use setjmp and longjmp: Whenever you call any Xlib functions, you setjmp before. Your I/O error handling function then longjmps away to get away from the I/O error without your process exiting.