Learning to Use X11

A tutorial discussing how to use X11 fully and effectively.
The Program, Part 2: Event Handling

To understand the next few lines, we have to reconsider one of the basic tenets of X11: it is a networked graphics framework in which the client (such as the program in Listing 1) and the graphics server might reside on physically remote machines. In such a situation, the failure of the network is a possibility that has to be anticipated. The XMapWindow command is issued on the client but executed on the server (note how X11's way of using those terms makes much more sense in the present context), which might not be available when the command is issued. The solution to this situation is to make the client/server communication asynchronous or event-driven. That is, XMapWindow sends its request to the server and returns immediately, without waiting for the completion of the server process. It is then up to the client to poll the server for successful execution of the previous command. The following lines do exactly that.

Lines 24 and 25: first, we need to select what kinds of events (such as mouse clicks, mouse movements, key strokes, etc.) we are interested in. Xlib.h defines a number of bit masks for the different kinds of events that can be bitwise ORed, if we are interested in several kinds of events. Here we are interested in the success of the previous mapping operation, and we therefore select the appropriate bit mask and inform the server of our choice, using XSelectInput. This function overwrites any previous setting with each new call.

Lines 27-30: XNextEvent blocks until an event occurs, sending the program to sleep so it does not consume CPU time while waiting. As a side effect, all non-empty output buffers are flushed with each call to XNextEvent, obviating explicit calls to XFlush. Since the StructureNotifyMask combines several events that are structural changes to the window and not just mapping events, we have to loop until the proper type of event has been reported. (If this presentation leaves questions, don't despair: hopefully a fuller treatment of X11 events will be the subject future articles.)

Lines 33-36: now that we can be certain the window is actually visible on the screen, we are finally ready to draw something to it. First, we define a GraphicsContext (GC), a struct that comprises information about the appearance (such as color, linestyle, etc.) of the graphical elements. Attributes of the GraphicsContext can be set at creation by providing a bit mask specifying the attributes as the third and an array of values as the fourth argument. Alternatively, attributes of the GC can be set individually by calling the appropriate functions.

Lines 39 and 40: draw two lines, forming an X on the screen. There are similar functions to draw points, arcs and rectangles, all taking coordinates relative to the current window. Remember to use these functions only with windows that you know are actually visible, not hidden or minimized. Drawing to an invisible window has no effect.

Lines 43-48: now that the graph (as it is) is complete, the program should wait for the user to click on the window to terminate it. Accordingly, we set the appropriate event mask and wait for the desired event. Note again that XNextEvent flushes all output buffers, so we are certain that the two lines indeed appeared before the mouse-click event occurred.

Lines 51 and 52: part of well-behaved C programming is responsible resource management. We therefore explicitly free the allocated resources, rather than let the program fall off the end and have the operating system clean up after us. As a side effect, XDestroyWindow unmaps the window in question automatically, so it disappears from the screen.


This concludes our analysis of the example program. If the source file is called x1.cc, the compile command would take the form:

g++ -I /usr/X11/include -L /usr/X11/lib -o x1 x1.cc -lX11

I have been using C++ throughout, so that I could use end-of-line comments and define variables wherever I needed them. The compiler option -I instructs the compiler where to look for the include files, while the -L option tells the linker where to find the libraries. The argument -lX11 (which has to go last on the command line) finally instructs the linker to link the library named libX11.so. Depending on your installation, the paths may be different.

The program should compile and run successfully. You may want to experiment with some of the parameter values or add further functionality. Don't be afraid to browse the Xlib documentation for additional functions or obtain more information on those functions used in the example program.

Two crucial issues that I had to omit in this article concern the handling of errors generated by X11, as well as the behavior of the window's contents when the window is resized, or minimized and maximized again (try it out). We will cover them and much more in future articles, when we take a closer look at X11 events.



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

how to run the program

szs's picture

-open terminal and type 'apt-get install libx11-dev'.this should download and install the x11 library.
-open the program and include the library 'X11/Xlib.h'.
-compile the program by typing 'g++ -o output x1.cc -lX11'
-run the program by typing ./output.

hope this helps....XD

Draw a bare window (without Close, Minimize, Maximize buttons)

Anonymous's picture

how to create a window described in the subject? I cannot find out the solution.
thanks and regards


x11 man

renu's picture

i m new to x11. i m not getting the point how to set the path be4 running x11 prog. and i m not getting the manual pages after writing the man command on the shell.can anybody help me??

how to link xlib

Anonymous's picture

how to link xlib

A Simple OpenGL Program Using GLUT and C

mattv's picture

Running FreeBSD 6.1, I find that example programs shown in "OpenGL Programming Guide, Fifth Edition" (Red Book), can be compiled as follows:

gcc -I /usr/X11R6/include -L /usr/X11R6/lib -o your_program your_program.c -lX11 -lGL -lglut

Red Book examples always use GLUT.

So, just to let you know...


Re: Learning to Use X11

Anonymous's picture


On the web there are some Xlib tutorials like this. They create one or two windows, draw few lines or arcs (some even in color) and some show the typical XLib program main loop like the following:

   Display* xDisplay;

   XEvent xEvent;


   xDisplay = XOpenDisplay(NULL);

   while(!done) {

      XNextEvent(xDisplay, &xEvent);

      ... // process the event



Unfortunately it's the point where the tutorials finish. I hope there will be some continuing of this tutorial.

For example I'm unable to find how to handle linux signals in the main loop. XNextEvent() doesn't return EINTR like libc blocking functions.

Imagine you would like to write trivial clock program for X and you need catch some SIGALRM or other signal every second to refresh the clock as well as catch X events.

How to handle such task without busy waiting?




Re: Learning to Use X11

Anonymous's picture

I just made binary coded decimal clock program as my first xlib program to use events, but I didn't use events to tell the time. I just made a for(;;){ loop with sleep(1); as the first statement (this function is defined in unistd.h for some reason, and the parameter 1 means 1 second). This statement keeps the program from being active all the time. After that I just used the functions in time.h to find the time. I am not sure what other non-xlib events you might want to intercept, but you might be able to do something like this.

Unfortunate Title

dlc's picture

What I expected from this article was how to use X, not code an X client. Change the title and you'll have an excellent resource (as how the article employs resources, not how an X user employs resources).

Re: Learning to Use X11

Anonymous's picture

The author must be using Debian because he said the latest version of XFree86 is 4.1.0 not 4.2.0.

Re: Learning to Use X11

masinick's picture

Stuff gets dated rather quickly. You're right, XFree86 does, indeed have 4.2.0 released, (and for all I know, they might even be past that now)! But 4.2.0 is new enough that only the latest distros are actually using it. For many vendors, their NEXT release will likely have 4.2.0 code, but 4.1.0 or even some 3.3.6 stuff is STILL pretty common, and not JUST for Debian-based systems, either.


Anonymous's picture

"We therefore explicitly free the allocated resources"

To be fussy, I guess we should call XFreeGC then also.

Looking forward for the next episode

servers and clients ... sure they are software

Anonymous's picture

Well, clients and servers are still software-only ...

the problem is that some twisted host and server - doh!

And don't think i'm one of those grey-bearded veterans.

The first thing our information science teacher said about servers:

"Servers are software, not hardware" (He said that in german, but most of you prefare a sort of english i guess *g*)

So: no problem reading the x11-manual - at least not by twisting server and client, the rest ... *caught*

Spank me if i'm wrong!

Dear oh dear... "Server" and "Client" were *never* twisted!

Anonymous's picture

If you think of the meaning of the words "server" and "client" it is difficult to get them confused, even when thinking in terms of X, instead of in terms of (say) a file server.

A "server" is something that provides a service. In the case of a file server, it is something that provides access to files over a network. In the case of X, the service provided is that of the drawing to the screen.

A "client" is something that requests the server to perform a task. In the case of the file server, it is requesting that a certain file be sent to it. In the case of X, it is asking the server to draw something to the screen.


Re: Learning to Use X11

Anonymous's picture

or a departmental server, connected to a larger number of (relatively dumb) X terminals.

Nope, that's wrong. Each X terminal would be a separate display (actually, separate host:display usually), not multiple screens. The dual- (or more) head example is a valid multi-screen example.

By the way, on Linux boxes at least, you can have multiple X displays running simultaneously (virtualized) by starting X from different virtual consoles (ie using ctrl-alt-F2 to log in, etc), by adding the display number (eg "startx -- :1"), the catch is that GNOME and KDE can't handle multiple instances of themselves on the same computer (you can run GNOME on one display and KDE on the other). Switch displays using ctrl-alt-F7, ctrl-alt-F8, etc.

Re: Learning to Use X11

Anonymous's picture

Multiple instances for one user of the WindowMaker window manager are also not supported.

Re: Learning to Use X11

Anonymous's picture

found the source, but you must do a


rather than


and you must use the following

g++ -I /usr/X11/include/X11 -L /usr/X11/lib -o x1 x1.cc -lX11

to compile on suse linux.

Re: Learning to Use X11

Anonymous's picture

i make a program with C, and then compile it like this :

cc -g -o myprog myprog.c -lX11

but it is error in X11...!!

can anyone help me...? please..!
did i must configure somethink...to make it clear...?

i use suse 8.2, and i just install xdevel-xxx.rpm

Re: Learning to Use X11

Anonymous's picture

it should read #include

Re: Learning to Use X11

Anonymous's picture

Where is the difference between

#include and #include?

Magical whitespace?

Re: Learning to Use X11

Anonymous's picture

I think the HTML of the original poster's comment got "filtered" by PHP nuke.

Re: Learning to Use X11

Anonymous's picture

Yes, sure, but what is the file to #include between the

/ /

then? 8-)

#include or #include

Anonymous's picture

#include <Xlib.h>
#include <X11/Xlib.h>

Re: Learning to Use X11

Anonymous's picture

god I think my brain has frozen on monday morning, I found th e source, compiled it and it work!!!!!


Re: Learning to Use X11

Anonymous's picture

I'd like to give this a go? but where's the source luke?


Anonymous's picture

The paragraph titles are links, Jar-Jar. Click them with your favourite pointing device.

Me sah

jar Jar's picture

Me sah no sah point divvy-sicer onna dee clikkers link.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState