简体   繁体   English

从另一个进程关闭XLib应用程序

[英]Close XLib application from another process

I have a Xlib-based program with an event loop that uses XNextEvent to receive and process relevant events. 我有一个基于Xlib的程序,其中包含一个使用XNextEvent接收和处理相关事件的事件循环。

I would like to be able to gracefully close this program from another process (actually from a shell script). 我希望能够从另一个进程(实际上来自shell脚本)优雅地关闭该程序。 I need to do some cleanup when closing, so I considered to setup a signal handler (for example for SIGUSR1) and when this signal is received, do the appropriate cleanup. 关闭时我需要做一些清理,所以我考虑设置信号处理程序(例如SIGUSR1),当收到此信号时,进行适当的清理。

My question is, how can I interrupt the (blocking) XNextEvent call from the signal handler? 我的问题是,如何从信号处理程序中断(阻塞) XNextEvent调用?

Any other suggestions? 还有其他建议吗?

I found a way to do this based on this SO question and this one . 我找到了一种基于这个SO问题这个 问题的方法

Basically you can use the ConnectionNumber() macro to get the fd that XNextEvent() is reading from. 基本上,您可以使用ConnectionNumber()宏来获取XNextEvent()正在读取的fd。 This lets me call select() myself to wait for data on the Xlib fd and some other fd. 这让我自己调用select()来等待Xlib fd 其他一些fd上的数据。 Now it is select() that is blocking, and not XNextEvent() . 现在它是阻塞的select() ,而不是XNextEvent() I can easily unblock select() from my signal handler by writing to the second fd. 通过写入第二个fd,我可以轻松地从信号处理程序中取消阻止select()

Pseudo-code for the event loop: 事件循环的伪代码:

/* 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 */
        }
    }
}

Assuming you have the process id, you can use the kill function: 假设您有进程ID,可以使用kill函数:

int kill(pid_t pid, int sig);

You can send any signal but SIGKILL ( SIGKILL cannot be handled) 您可以发送任何信号,但SIGKILLSIGKILL无法处理)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM