Search code examples
clinuxwindowx11

Simple C Program that creates 2 X11 windows


I want to create 2 windows in linux that I'll later draw in from a separate thread. I currently have a non-deterministic bug where the second window that I create sometimes doesn't get created (no errors though).

Here is the code.

static void create_x_window(Display *display, Window *win, int width, int height)
{
    int screen_num = DefaultScreen(display);
    unsigned long background = WhitePixel(display, screen_num);
    unsigned long border = BlackPixel(display, screen_num);
    *win = XCreateSimpleWindow(display, DefaultRootWindow(display), /* display, parent */
        0,0, /* x, y */
        width, height, /* width, height */
        2, border, /* border width & colour */
        background); /* background colour */
    XSelectInput(display, *win, ButtonPressMask|StructureNotifyMask);
    XMapWindow(display, *win);

}

int main(void) {
    XInitThreads(); // prevent threaded XIO errors
    local_display = XOpenDisplay(":0.0");

    Window self_win, remote_win;
    XEvent self_event, remote_event;

    create_x_window(local_display, &remote_win, 640,480);
    // this line flushes buffer and blocks so that the window doesn't crash for a reason i dont know yet
    XNextEvent(local_display, &remote_event);


    create_x_window(local_display, &self_win, 320, 240);
    // this line flushes buffer and blocks so that the window doesn't crash for a reason i dont know yet
    XNextEvent(local_display, &self_event);

    while (1) {

    }
    return 0;
}

I don't really care for capturing input in the windows, but I found a tutorial that had XSelectInput and XNextEvent (in an event loop) and I was having trouble making this work without either.


Solution

  • It's not a bug, it's a feature. You left out the event loop.

    Although you cleverly called XNextEvent twice, the X protocol is asynchronous so the server may still be setting up the actual window while you call XNextEvent, so there is nothing to do.

    Tutorial here.