【问题标题】:Taking screenshots with XLib freezes my computer用 XLib 截屏会冻结我的电脑
【发布时间】:2014-12-30 00:22:36
【问题描述】:

所以我一直在玩 XLib,我尝试用 C++ 编写一个程序,它可以简单地截取屏幕截图并将其显示在窗口中,从而创建一种隧道效果。它工作得很好,几秒钟。然后我的电脑(顺便说一下,运行 Ubuntu)开始以非常非常慢的帧速率运行,我的鼠标几乎没有响应,关闭窗口无法停止它,按 ctrl-c 无法停止它,然后它只是完全冻结,我别无选择使用电源按钮手动关闭它并重新启动计算机(之后,它似乎工作正常?)。

现在,XLib 是一个非常奇怪的库,没有很好的文档,所以我知道我只是从根本上做错了,但我的代码非常简单,以至于我不知道它可能是什么。我尝试了各种方法(注释掉某些功能,使用 usleep 在帧之间暂停它),但是当它不起作用并且必须重新启动计算机时,每一个新想法都令人沮丧。所以也许你们当中有人知道发生了什么?

这是我的代码:

#include <X11/Xlib.h>
int main(){
    //Initializes some values
    Display* display=XOpenDisplay(0);
    Window root=DefaultRootWindow(display);
    XWindowAttributes att;
    XGetWindowAttributes(display, root, &att);
    //att.width and att.height now are the width and height of the screen
    int screen=DefaultScreen(display);
    Window window=XCreateSimpleWindow(display, root, 0, 0,
                         att.width, att.height, 1,
                         BlackPixel(display, screen),
                         WhitePixel(display, screen));
    GC graphics=XCreateGC(display, window, 0, NULL);

    //puts window on screen
    XMapWindow(display, window);
    while(1){
        //This gets the screenshot
        XImage* ximg=XGetImage(display, root, 0, 0,
                           att.width, att.height,
                           AllPlanes, ZPixmap);
        //This puts the screenshot in the window "window"
        XPutImage(display,window, graphics,  ximg,
                  0,0,0,0, att.width, att.height);
        //frees the data allocated to ximg
        XFree(ximg);
    }
}

(这应该用一个简单的 g++ screentest.cpp -lX11 编译)

对于它的价值,我没有从中收集到任何解决方案的一些信息丰富的网页是:

The man page for XGetImage and XPutImage

The man page for XFree, although I really don't think this is the problem

This Stack Overflow question seems relevant - but it doesn't have any answers

我还查看了相当多的其他 Stack Overflow 问题,虽然相当多的问题看起来可能相关,但我没有看到任何与我的问题直接相关的内容。

感谢您提供的任何帮助。

【问题讨论】:

  • 你是如何开始你的计划的?

标签: c++ linux ubuntu screenshot xlib


【解决方案1】:

您说您添加了代码以在调用之间休眠。那将是一件好事。尝试添加比您已经尝试过的更长的睡眠间隔。

还可以考虑使用计数器,这样您就不会永远调用它。我猜这个问题要么是内存使用失控,要么只是一个无限循环。不管怎样,加入一些东西,让程序自行停止,而不是依靠你手动退出。

【讨论】:

  • 我使用了一个计数器退出,它在 1000 次调用时或多或少地工作正常,但在 4000 次调用时就坏了,我并没有真正尝试获得更具体的数字(我想我实际上可以打印出来数字并在它冻结时专门找到,但我不是很感兴趣)。延长睡眠时间似乎只是使其持续时间更长——尽管可以承认,因为它需要几千次调用才能杀死计算机,而且它似乎总是会杀死计算机,所以我没有尝试过睡眠时间超过十分之一秒。
猜你喜欢
  • 2014-06-25
  • 1970-01-01
  • 1970-01-01
  • 2012-01-05
  • 2022-06-19
  • 2019-04-06
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多