c - 读取行 C : force return of certain text in readline()

标签 c readline

我正在尝试允许中断导致 readline 返回某个值。这是一个最小的例子:

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

void handler (int status)
{
   rl_replace_line("word",0);
   rl_redisplay();
   rl_done = 1;
}

int main (int argc, char** argv)
{
   char* entry;
   signal(SIGINT,handler);
   entry = readline("");

   printf("\nEntry was: %s\n", entry);
   return 0;
}

如果我运行此代码并按 Control-C,在我按下 ENTER 后,它肯定会打印“Entry was: word”。但我希望它在用户不需要按 ENTER 的情况下这样做。我基本上只想在收到中断信号时将条目设置为“字”,从而结束 readline 功能。我一直无法找到有关如何结束 readline 循环并返回特定值的任何文档(我确定它在那里,但我还没有找到它)。

我试过的一件事是添加

 (*rl_named_function("accept-line"))(1,0);

在处理程序的末尾,但它没有立即将文本发送到“entry”。

最佳答案

我想我有你想要的东西在这里运行。

#include <stdio.h>
#include <signal.h>
#include <readline/readline.h>
int event(void) { }
void handler (int status)
{
   rl_replace_line("word",0);
   rl_redisplay();
   rl_done = 1;
}

int main (int argc, char** argv)
{
   char* entry;
   rl_event_hook=event;
   signal(SIGINT,handler);
   entry = readline("");

   printf("\nEntry was: %s\n", entry);
   return 0;
}

secret 是 rl_done 只在事件循环中检查。当您给它一个空事件 Hook 函数时,它会检查 rl_done 并退出。

关于c - 读取行 C : force return of certain text in readline(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53165704/

相关文章:

python - 以 4 为一组从巨大的文本文件中读取行

c - 声明 -n 参数以在命令行中接受整数 - C

c - 一个二进制文件中的两个过滤器驱动程序导致第二个驱动程序出现系统错误 2

c - 在 Linux 中运行的进程如何确定它已挂起多长时间?

c - 将 GNU readline 提示设置为 NULL 会导致自定义提示被覆盖

c# - 如何在输入字符串 C# 中允许货币符号

无法理解涉及指针的 C 程序的一小部分

c - GdkPixbuf-CRITICAL ** : gdk_pixbuf_get_width: assertion `GDK_IS_PIXBUF (pixbuf)' failed

c - 如何使用 libreadline 在套接字上进行选择?

c - 用 C 读取客户端的所有行