简体   繁体   English

GNU Readline:是否有取消readline输入请求的功能?

[英]GNU Readline: Is there a function that cancels readline input request?

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

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. 实际上,您无需取消任何操作,只需(暂时)退出rl_callback_read_char循环即可执行所需的任何操作。 This can even happen before the user has sent an ENTER, but only after a keypress . 这甚至可以在用户发送ENTER 之前发生,但只能在按键之后发生

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

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 (eg by setting an alarm() ). 如果要在没有按键的情况下“取消”,则必须使用信号(例如,通过设置alarm() )来中断rl_callback_read_char()内部的read()系统调用。 Be aware, however, that readline installs its own signal handlers . 但是请注意,readline 会安装自己的信号处理程序

A slightly more sophisticated method would be to insert into the loop a select() on two file descriptors, stdin and eg 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.. 稍微复杂一点的方法是在循环中的两个文件描述符stdin和例如管道( self-pipe技巧 )上插入一个select() ),以使用第二个描述符(和/或超时)“唤醒” “ select() ,然后像下面的示例一样退出循环。

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

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