简体   繁体   English

在终端内隔离stdin和stdout

[英]Isolating stdin and stdout within a terminal

I'm developing a CLI program, in C, for my systems class project, and it needs to display incoming text while maintaining a command prompt. 我正在为C系统类项目开发一个CLI程序,它需要在保持命令提示符的同时显示传入的文本。 Left alone, the incoming text will saw through whatever one tries to type. 单独留下,传入的文本将通过任何尝试键入的内容进行查看。 In other applications I've seen the incoming text print above(or below) the prompt itself. 在其他应用程序中,我看到输入文本打印在提示本身上方(或下方)。 Is there any way to implement this in ANSI escapes? 有没有办法在ANSI转义中实现这个? ncurses seems like overkill. ncurses似乎有点矫枉过正。

You can print \\r to erase the prompt: It will return the cursor to the beginning of the current line. 您可以打印\\r来删除提示:它会将光标返回到当前行的开头。 You can then print your output followed by some spaces to clear out any remaining input characters, newline, and reprint the prompt. 然后,您可以打印输出,然后打印一些空格以清除任何剩余的输入字符,换行符,并重新打印提示。

With ANSI sequences or terminal-specific libraries you can do even more, but this I think is all you can do reliably using only ASCII. 使用ANSI序列或终端专用库,您可以做更多,但我认为只有使用ASCII才能可靠地完成。 Apart from printing 242 blank lines to redraw the whole screen, of course. 当然,除了打印242个空行以重绘整个屏幕外。

Edit: Sorry, I didn't answer the ANSI part properly. 编辑:对不起,我没有正确回答ANSI部分。 With cursor movement control codes and printing space over existing characters, you can pretty much do anything, and there are some convenience actions to help you, such as "delete line". 使用光标移动控制代码和现有字符上的打印空间,您几乎可以执行任何操作,并且有一些便利操作可以帮助您,例如“删除行”。 But keep in mind that Windows doesn't play nice w/ ANSI post XP, and neither are other systems guaranteed to. 但请记住,Windows不能与ANSI post XP一起使用,并且其他系统都不能保证。

For one thing, if you want to maintain a prompt, while printing, you can not use things like scanf. 首先,如果要在打印时保持提示,则不能使用scanf之类的东西。 You have to intercept keyboard events or use a non waiting method to get input. 您必须拦截键盘事件或使用非等待方法来获取输入。 Then you can get the terminal number of lines (n) and print the last n-1 lines of your output, and then a prompt. 然后,您可以获得行的终端数(n)并打印输出的最后n-1行,然后提示。

my2c MY2C

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

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