title: How to stop the execution of a running code in x11
body: <p>I have a program that draws on a x11 window and I'd like to quit it as soon as I press any key.</p>
  <p>With the code I have, I cannot stop the program with a keypress until the <code>for</code> loop has finished drawing on the window (moving a red oval from left to right). I'd like to quit the <code>for</code> loop as soon as a key is pressed regardless of the state of the drawing (finished or not) even if the <code>for</code> loop hasn't finished executing its part.</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;X11/Xlib.h&gt;
  #include &lt;X11/Xutil.h&gt;
  #include &lt;unistd.h&gt;
  
  Display *dis;
  Window win;
  
  unsigned long GetColor(char *color_name)
  {
    Colormap cmap;
    XColor near_color, true_color;
    cmap = DefaultColormap(dis, 0);
    XAllocNamedColor(dis, cmap, color_name, &amp;near_color, &amp;true_color);
    return(near_color.pixel);
  }
  
  int main(int argc, char **argv)
  {
    if ((dis = XOpenDisplay(NULL)) == NULL) { printf(&quot;Error XOpenDisplay\n&quot;); return 1; }
  
    win = XCreateSimpleWindow(dis, RootWindow(dis, 0), 1, 1, 256, 256, 0, BlackPixel(dis, 0), BlackPixel(dis, 0));
  
    XSelectInput(dis, win, ExposureMask | KeyPressMask | KeyReleaseMask);
  
    XMapWindow(dis, win);
    XFlush(dis);
  
    XEvent ev;
    do {
      XNextEvent(dis, &amp;ev);
    } while (ev.type != Expose);
  
    GC gc;
    gc = XCreateGC(dis, DefaultRootWindow(dis), 0, 0);
    XSetFunction(dis, gc, GXxor);
  
    while (!(XCheckWindowEvent(dis, win, KeyPressMask, &amp;ev) || XCheckTypedWindowEvent(dis, win, ClientMessage, &amp;ev))) {
  
      XNextEvent(dis, &amp;ev);
  
      // quit program as soon as a key is pressed
      if (ev.type == KeyPress &amp;&amp; XEventsQueued(dis, QueuedAfterReading)) {
        goto finish;
      }
      // I'd like to quit from this for loop as soon as a key is pressed
      for (int t = 0; t &lt; 150; t++) {
  
        // quit program as soon as a key is pressed
        if (ev.type == KeyPress &amp;&amp; XEventsQueued(dis, QueuedAfterReading)) {
          goto finish;
        } else {
          // draw a red oval and move it from left to right
          XSetForeground(dis, gc, BlackPixel(dis, 0) ^ GetColor(&quot;red&quot;));
          XFillArc(dis, win, gc, t * 5 + 10, t * 3 + 40, 80, 40, 0, 360 * 64);
          XSetForeground(dis, gc, BlackPixel(dis, 0) ^ GetColor(&quot;red&quot;));
          usleep(20000);
          XFillArc(dis, win, gc, t * 5 + 10, t * 3 + 40, 80, 40, 0, 360 * 64);
          //XSync(dis, True);
        }
      }
    }
  
  finish:
    XFreeGC(dis, gc);
    XDestroyWindow(dis, win);
    XCloseDisplay(dis);
    return(0);
  }
  </code></pre>
  <p>I execute it with:
  <code>gcc draw.c -lX11 &amp;&amp; ./a.out</code></p>