【发布时间】:2021-08-12 14:46:38
【问题描述】:
我关注了How to upload 32 bit image to server-side pixmap 和XDestroy(ximg); segfaults。
#include <stdlib.h>
#include <string.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
int
main(int argc, char **argv) {
Display *dpy;
Window root;
Screen *screen;
GC gc;
XImage *ximg;
Pixmap pm;
int depth, h, w;
char *img;
dpy = XOpenDisplay(0);
if (!dpy) {
fputs("cannot open display\n", stderr);
return 1;
}
screen = DefaultScreenOfDisplay(dpy);
h = HeightOfScreen(screen);
w = WidthOfScreen(screen);
root = DefaultRootWindow(dpy);
depth = DefaultDepth(dpy, DefaultScreen(dpy));
img = malloc(depth/8 * h * w);
if (img == NULL) {
perror("malloc() failed");
return 1;
}
memset(img, 0xFF, depth/8 * h * w);
ximg = XCreateImage(dpy, CopyFromParent, depth, ZPixmap, 0, img, w, h, 32, 0);
pm = XCreatePixmap(dpy, root, w, h, depth);
gc = XCreateGC(dpy, pm, 0, NULL);
XPutImage(dpy, pm, gc, ximg, 0, 0, 0, 0, w, h);
XCopyArea(dpy, pm, root, gc, 0, 0, w, h, 0, 0);
free(img);
XFreePixmap(dpy, pm);
XDestroyImage(ximg);
XFreeGC(dpy, gc);
XCloseDisplay(dpy);
return 0;
}
另外,根据How to draw an image from file on window with Xlib,我应该包括类似
XEvent ev;
while (1) {
XNextEvent(dpy, &ev);
if (ev.type == Expose)
XCopyArea(dpy, pm, root, gc, 0, 0, w, h, 0, 0);
}
在清理之前,但我如何/何时提供系统资源?
更新
显然free(img); 导致了段错误,因为XDestroyImage(ximg); 本身正在释放图像。但是,我应该把那个事件循环放在哪里,它应该有什么终止条件,以便我可以相应地释放系统资源?
【问题讨论】:
-
你不应该在一篇文章中写两个独立的问题。与其将答案编辑到问题中,不如写一个答案。 (是的,您可以回答自己的问题。)这将表明问题已得到回答。我只是想写一个引用documentation of XDestroyImage 的评论。我建议在答案中添加这样的内容。我进一步建议为仍未回答的部分发布一个单独的问题。
-
如果你想在根窗口上绘图,你需要有一个常规的X11客户端程序在根窗口上绘图,然后运行永远(或直到您不再需要该图像)。如果你想设置一个根像素图而不让你的程序运行,让X服务器处理它,看看here。