[英]How to stop the execution of a running code in x11
我有一個程序在 x11 window 上繪制,我想在按下任意鍵后立即退出它。
使用我擁有的代碼,在for
循環完成 window 上的繪制(從左向右移動紅色橢圓形)之前,我無法通過按鍵停止程序。 我想在按下一個鍵后立即退出for
循環,而不管繪圖的 state(完成與否),即使for
循環尚未完成其部分執行也是如此。
#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <unistd.h>
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, &near_color, &true_color);
return(near_color.pixel);
}
int main(int argc, char **argv)
{
if ((dis = XOpenDisplay(NULL)) == NULL) { printf("Error XOpenDisplay\n"); 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, &ev);
} while (ev.type != Expose);
GC gc;
gc = XCreateGC(dis, DefaultRootWindow(dis), 0, 0);
XSetFunction(dis, gc, GXxor);
while (!(XCheckWindowEvent(dis, win, KeyPressMask, &ev) || XCheckTypedWindowEvent(dis, win, ClientMessage, &ev))) {
XNextEvent(dis, &ev);
// quit program as soon as a key is pressed
if (ev.type == KeyPress && 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 < 150; t++) {
// quit program as soon as a key is pressed
if (ev.type == KeyPress && XEventsQueued(dis, QueuedAfterReading)) {
goto finish;
} else {
// draw a red oval and move it from left to right
XSetForeground(dis, gc, BlackPixel(dis, 0) ^ GetColor("red"));
XFillArc(dis, win, gc, t * 5 + 10, t * 3 + 40, 80, 40, 0, 360 * 64);
XSetForeground(dis, gc, BlackPixel(dis, 0) ^ GetColor("red"));
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);
}
我執行它: gcc draw.c -lX11 &&./a.out
您面臨的問題與usleep
有關。
基本上, usleep
將掛起程序運行的線程,直到設置的時間間隔結束。 您可以通過向它發送信號(例如SIGKILL
或SIGQUIT
)來中斷它,但這是只能在程序外部而不是在程序內部完成的事情。
您可能希望查看此頁面以了解usleep
的工作原理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.