Obtaining List of all Xorg Displays

void-pointer picture void-pointer · Jul 6, 2012 · Viewed 20.1k times · Source

I would like to know how I can obtain a list of all Xorg displays on my system, along with a list of screens associated with each display. I spent some time looking through the Xlib documentation, but was not able to find a function that does what I want. Please assume that I have no other dependencies other than a POSIX-complaint OS and X (e.g., no GTK). If what I ask is not possible assuming these minimal dependencies, then a solution using other libraries is fine.

Thank you very much for your help!

Answer

netcoder picture netcoder · Jul 6, 2012

The only way I know of to get a list of displays is to check the /tmp/.X11-unix directory.

Once you do that, you can use Xlib to query each display for more information.

Per example:

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <X11/Xlib.h>

int main(void) {
    DIR* d = opendir("/tmp/.X11-unix");

    if (d != NULL) {
        struct dirent *dr;
        while ((dr = readdir(d)) != NULL) {
            if (dr->d_name[0] != 'X')
                continue;

            char display_name[64] = ":";
            strcat(display_name, dr->d_name + 1);

            Display *disp = XOpenDisplay(display_name);
            if (disp != NULL) {
                int count = XScreenCount(disp);
                printf("Display %s has %d screens\n",
                    display_name, count);

                int i;
                for (i=0; i<count; i++)
                    printf(" %d: %dx%d\n",
                        i, XDisplayWidth(disp, i), XDisplayHeight(disp, i));

                XCloseDisplay(disp);
            }
        }
        closedir(d);
    }

    return 0;
}

Running the above gives me this output with my current displays/screens:

Display :0 has 1 screens
 0: 3046x1050
Display :1 has 2 screens
 0: 1366x768
 1: 1680x1050

Never found a better way of listing X displays other than that. I'd very much like to know if any better alternative exists.