我有一个基于Xlib的程序,带有使用XNextEvent
接收和处理相关事件的事件循环。
我想能够从另一个进程(实际上是从一个shell脚本)优雅地closures这个程序。 closures时我需要做一些清理工作,所以我考虑设置一个信号处理程序(例如SIGUSR1),并在接收到这个信号时进行适当的清理。
我的问题是,我怎么能中断信号处理程序的(阻塞) XNextEvent
调用?
还有其他build议吗?
我找到了一个基于这个SO问题和这个 问题的方法 。
基本上,您可以使用ConnectionNumber()
宏来获取XNextEvent()
正在读取的fd。 这让我自己调用select()
来等待Xlib fd 和其他fd上的数据。 现在是select()
,而不是XNextEvent()
。 我可以通过写入第二个fd来轻松地从我的信号处理程序中取消阻塞select()
。
事件循环的伪代码:
/* Get X11 fd */ x11_fd = ConnectionNumber(display); while(1) { /* Create a File Description Set containing x11_fd and other_fd */ FD_ZERO(&in_fds); FD_SET(x11_fd, &in_fds); FD_SET(other_fd, &in_fds); /* Wait for X Event or exit signal */ ret = select(nfds, &in_fds, ...); if (FD_ISSET(other_fd, &in_fds) { /* Do any cleanup and exit */ } else { while (XEventsQueued(display, QueuedAlready) > 0) { /* Process X events */ } } }
假设你有进程ID,你可以使用kill
函数:
int kill(pid_t pid, int sig);
您可以发送任何信号,但SIGKILL
( SIGKILL
无法处理)