非阻塞标准输入输出 [英] Non-blocking stdio
问题描述
我工作,这将在用户输入从控制台服用以及在单独的线程printfing出的程序。我想避免用户所在中途打字什么情况,一个printf在光标一起并打印本身自带。
I'm working on a program which will be taking in user input from the console as well as printfing out in a separate thread. I want to avoid situations where the user is halfway through typing something in and a printf comes along and prints itself at the cursor.
有没有办法做到非阻塞IO在c从控制台窗口?理想情况下,捕捉关键presses或类似的东西,这样什么类型的用户不会出现在屏幕上。我在Ubuntu发展,这是最好的,如果我没有使用之类的东西ncurses的。
Is there a way to do non-blocking io in c from the console window? Ideally, capturing keypresses or something like that such that what the user types doesn't appear on the screen. I'm developing in Ubuntu, and it's best if I don't have to use things like ncurses.
推荐答案
使用的termios
您可以禁用终端回送:
using termios
you can disable terminal echoing:
#include <termios.h>
struct termios oflags, nflags;
tcgetattr(fileno(stdin), &oflags);
nflags = oflags;
nflags.c_lflag &= ~ECHO;
nflags.c_lflag |= ECHONL;
if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) {
/* handle error */
}
然后退出之前(使用 atexit对
)必须恢复终端:
if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) {
/* handle error */
}
这篇关于非阻塞标准输入输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!