GNU Readline:是否存在取消readline输入请求的功能? [英] GNU Readline: Is there a function that cancels readline input request?

查看:133
本文介绍了GNU Readline:是否存在取消readline输入请求的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是GNU Readline的新手,所以我想知道是否存在可以取消readline()请求的函数?

I'm new to GNU Readline, so I want to know if there exist a function that can cancel readline() request?

推荐答案

为此,您必须使用rl_callback_read_char循环即可执行所需的任何操作.这甚至可能在用户发送ENTER之前 发生,但是仅在按键后发生.

To do this, you'll have to use the alternate (or "callback") interface to readline. There is actually no need to cancel anything, you just (temporarily) step out of the loop around rl_callback_read_char to do whatever needs to be done. This can even happen before the user has sent an ENTER, but only after a keypress.

#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>

void line_handler(char *line) { /* This function (callback) gets called by readline                    
                                   whenever rl_callback_read_char sees an ENTER */
  printf("%s? Hah!!\n", line);
}

int main() {
  rl_callback_handler_install("Ask a question: ", &line_handler);

  while (1) {
    rl_callback_read_char();
    if (strstr(rl_line_buffer, "you")) { /* They're asking about *me* =:-0 */
      printf("\nNo personal questions please! Goodbye!\n");
      break;
      /* or make a snarky remark and continue */
    }
  }
}

如果要在没有按键的情况下取消",则必须使用信号(例如通过设置alarm())来中断rl_callback_read_char()内部的read()系统调用.但是请注意,readline 会安装自己的信号处理程序.

If you want to "cancel" without a keypress, you'll have to interrupt the read() syscall inside the rl_callback_read_char() using a signal (e.g. by setting an alarm()). Be aware, however, that readline installs its own signal handlers.

稍微复杂一点的方法是将两个文件描述符(stdin和例如)上的select()插入循环.管道(自管道技巧)使用第二个描述符(和/或超时)以唤醒" select(),然后像下面的示例一样退出循环.

A slightly more sophisticated method would be to insert into the loop a select() on two file descriptors, stdin and e.g. a pipe (the self-pipe trick), to use this second descriptor (and/or a timeout) to "wake up" the select(), and then step out of the loop just like in the example below..

这篇关于GNU Readline:是否存在取消readline输入请求的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆