Obtaining List of all Xorg Displays
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: 3046x1050Display :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.
Like netcoder wrote, the problem has two distinct parts:
Connection to the X server
The process establishes a connection to an X server using
XOpenDisplay()
. The connection is torn down usingXCloseDisplay()
. netcoders code in this thread is a good example of how to do it correctly.As netcoder mentioned, the problem is that there is no reliable way find out which X servers a process can connect to. His code checks the typical location where the X sockets are,
/tmp/.X11-unix/
. That approach does not work at all if the user is remotely connected, for example via SSH (with X forwarding enabled). In that case there is really only theDISPLAY
environment variable (and perhaps some trickery wrt.~/.Xauthority
files).Unfortunately, I do not know of any better method either. I personally prefer to use a per-user configuration file -- say
~/.application/displays
--, where the user can list the server names the application should try to connect in the same format as theDISPLAY
environment variable, in addition to the default one. It is not automatic (netcoder's code is), but this approach suits me better.Finding out about the screens provided by an X server
XScreenCount()
will return the number of screens provided by the X server the process is currently connected to. If you only need the screen dimensions, follow netcoders example. For more detailed information, useXScreenOfDisplay(Display,index)
to obtain theScreen
pointers;0
<=index
<XScreenCount(Display)
.In C code, the macros
ScreenCount()
andScreenOfDisplay()
are usually a bit more efficient than the actual function calls.