C termios和printf问题

C termios和printf问题,c,terminal,printf,termios,C,Terminal,Printf,Termios,我正在使用Lubuntu和LX终端 我(有点)毫不羞耻地从一个提供c非阻塞键盘输入详细信息的数据库中复制了这段代码的基础 这是第一部分: #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/select.h> #include <termios.h> using namespace std;

我正在使用Lubuntu和LX终端

我(有点)毫不羞耻地从一个提供c非阻塞键盘输入详细信息的数据库中复制了这段代码的基础

这是第一部分:

#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;
    }
}
到主函数的末尾

这是怎么回事?在释放所有printf函数的程序结束时,是否会发生某种魔法


当程序仍在运行时,如何使其打印?

显然,您是过度缓冲的受害者

尝试使用禁用缓冲

要完全禁用标准输出上的缓冲,请执行以下操作:

setvbuf(stdout, (char *)NULL, _IONBF, 0); 
要为每行启用缓冲,请执行以下操作:

setvbuf(stdout, (char *)NULL, _IOLBF, 0); 
// or
setlinebuf(stdout); 

printf
是一个缓冲输出,因此在每次printf之后,您应该关闭缓冲(
setbuf(stdout,NULL);
)或刷新它(
fflush(stdout);
),效果非常好!谢谢你的帮助!
setvbuf(stdout, (char *)NULL, _IONBF, 0); 
setvbuf(stdout, (char *)NULL, _IOLBF, 0); 
// or
setlinebuf(stdout);