如何在使用 GNU readline 从 stdin 读取时将消息输出到另一个线程上的 stdout 而不会弄乱输入?
抱歉标题太长了。我正在用 C 开发一个网络程序,它可以在标准输出上显示从网络接收的消息,并通过 GNU readline 库接受标准输入上的用户输入。 问题是,当用户通过 readline 在主线程上输入命令时,网络消息到达并输出到 stdout,这将产生如下内容:
场景:
输入:1234567890
网络消息:您好
当用户刚刚输入“7”时网络消息到达
终端上的实际输出:
输入> 1234567您好
890_
有没有办法得到这样的输出?
你好
输入> 1234567890_
ps _ 是光标。
提前致谢!
Sorry for the long title. I am developing a network program in C which may display messages received from network on stdout and accept user input on stdin via the GNU readline library.
The problem is, when the user is typing commands on the main thread via readline, a network message arrives and output to stdout, which will produce something like this:
Scenario:
Input: 1234567890
Network message: Hello
The network message arrives when the user just typed "7"
Actual output on terminal:
Input> 1234567Hello
890_
Is there a way to have the output like this?
Hello
Input> 1234567890_
p.s. _ is the cursor.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好的,我在四处搜索后找到了解决方案,并对 printf() 进行了以下替换。通过使用 rl_replace_line("", 0) 它将清除当前行并将光标置于行首,然后我可以打印一行消息,然后恢复 readline 提示,将原始行替换回原位,然后恢复光标位置。
但是,此 hack 要求对此 printf 函数的任何调用都在末尾包含 \n,否则该行将被 readline 覆盖。
OK I have found a solution to this after searching around and made the following replacement to printf(). By using rl_replace_line("", 0) it will clear the current line and place the cursor at the start of line, then I can print a line of message, and then restore the readline prompt, replace the original line back in place, and restore the cursor position.
However, this hack requires any call to this printf function to include a \n at the end, otherwise the line will be overwritten by readline.
转储 readline 并读取用户输入的每个字符。如果在用户输入时收到任何网络消息,请清除当前行,输出网络消息,然后重新打印用户当前输入的行。
这看起来可能需要做很多工作,但这是我现在想到的唯一方法。
如果你转储readline,那么你可以使用curses,这会让事情变得更容易......
Dump
readline
and read everychar
the user is inputting. If you get any network messages while the user is inputting clear the current line, output the network message, then reprint the line the user is currently inputting.That might seem like a lot of work, but it's the only way that comes to my mind right now.
If you do dump
readline
then you can usecurses
which makes it easier...您应该在这两个线程之间进行某种同步。互斥锁或只是从一个线程到另一个线程的标志,指示它正在标准输入或标准输出上工作。
You should put some kind of synchronization between those two threads. A mutex lock or just a flag from one thread to another indicating that it is working on the stdin or stdout.
这可以使用 curses(3) 库来完成。
This can be done using the curses(3) library.