我想模拟很多关键的新闻事件。我使用XTestFakeKeyEvent
找到了一个解决方案,但是当我模拟超过210次时,我的程序会提出“达到的最大客户端数”分段错误。我不知道如何解决这个问题。
我的代码在这里:
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/extensions/XTest.h>
#include <stdio.h>
#define PRESS_UP 0
#define PRESS_DOWN 1
#define PRESS_LEFT 2
#define PRESS_RIGHT 3
#define PRESS_ENTER 4
#define PRESS_ESC 5
#define PRESS_HOME 6
Display *display;
unsigned int keycode;
int press(int key){
display = XOpenDisplay(NULL);
if(key == PRESS_UP)
keycode = XKeysymToKeycode(display, XK_Up);
else if(key == PRESS_DOWN)
keycode = XKeysymToKeycode(display, XK_Down);
else if(key == PRESS_LEFT)
keycode = XKeysymToKeycode(display, XK_Left);
else if(key == PRESS_RIGHT)
keycode = XKeysymToKeycode(display, XK_Right);
else if(key == PRESS_ENTER)
keycode = XKeysymToKeycode(display, XK_Return);
else if(key == PRESS_ESC)
keycode = XKeysymToKeycode(display, XK_Escape);
else if(key == PRESS_HOME)
keycode = XKeysymToKeycode(display, XK_Home);
XTestFakeKeyEvent(display, keycode, True, 0);
XTestFakeKeyEvent(display, keycode, False, 0);
XFlush(display);
return 0;
}
int main(int argc, char *argv[]){
int count = 0;
while (count < 500){
press(PRESS_UP);
printf("count =%d\n" ,count);
count ++;
}
}
输出:
$ gcc -lXtst -lX11 Util_KeyPressSimulator.c
$ ./a.out
count =0
^[[Acount =1
^[[Acount =2
...
^[[Acount =208
^[[Acount =209
^[[Acount =210
^[[AMaximum number of clients reachedSegmentation fault
请帮助,谢谢。
答案 0 :(得分:12)
您每次迭代都进行XOpenDisplay
而没有匹配的XCloseDisplay
。考虑在循环外的main()
中打开显示一次,然后在退出前关闭它。