我和LXterminal一起使用Lubuntu。
我(在某种程度上)无耻地从一个给出c非阻塞键盘输入细节的stack overflow answer中复制了这段代码的基础。
这是第一部分:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <termios.h>
using namespace std;
struct termios orig_termios;
void reset_terminal_mode()
{
tcsetattr(0, TCSANOW, &orig_termios);
}
void set_conio_terminal_mode()
{
struct termios new_termios;
/* take two copies - one for now, one for later */
tcgetattr(0, &orig_termios);
memcpy(&new_termios, &orig_termios, sizeof(new_termios));
/* register cleanup handler, and set the new terminal mode */
atexit(reset_terminal_mode);
cfmakeraw(&new_termios);
tcsetattr(0, TCSANOW, &new_termios);
}
int kbhit()
{
struct timeval tv = { 0L, 0L };
fd_set fds;
FD_ZERO(&fds);
FD_SET(0, &fds);
return select(1, &fds, NULL, NULL, &tv);
}
int getch()
{
int r;
unsigned char c;
if ((r = read(0, &c, sizeof(c))) < 0) {
return r;
} else {
return c;
}
}这里有一个主函数,它显示了一些奇怪的行为。
int main(int argc, char *argv[])
{
unsigned int stor;
set_conio_terminal_mode();
for(int i = 0; i < 6; i++){
while (!kbhit()) {} /* wait */
stor = getch(); /* consume the character */
reset_terminal_mode();
printf("\033[38;33m%i \033[38;0m", stor);
set_conio_terminal_mode();
}
printf("more text\n");
}这个主循环所做的是得到6个字符块(例如。输入6次或两次箭头键。)但是,在它说printf的地方,在程序完成之前没有打印输出。
当您添加
while(1){}主要功能的结束。
这是怎么回事?是否有某种魔法发生在程序的末尾,释放所有的printf函数?
当程序仍在运行时,如何使其打印?
发布于 2013-05-26 20:52:47
显然,你是过度缓冲的受害者。
尝试使用setvbuf禁用缓冲。
要完全禁用stdout上的缓冲:
setvbuf(stdout, (char *)NULL, _IONBF, 0); 要为每一行启用缓冲:
setvbuf(stdout, (char *)NULL, _IOLBF, 0);
// or
setlinebuf(stdout); https://stackoverflow.com/questions/16763519
复制相似问题