【问题标题】:C termios and printf issueC termios 和 printf 问题
【发布时间】:2013-05-21 17:45:55
【问题描述】:

我正在使用带有 LXterminal 的 Lubuntu。

我(有些)厚颜无耻地从stack overflow answer 复制了这段代码的基础,它提供了有关 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;
    }
}

这是一个 ma​​in 函数,它显示了一些奇怪的行为。

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 个字符块(例如 ENTER 6 次或箭头键两次。)但是,在它说 printf 的地方,在程序完成之前没有打印输出。

添加后效果会更好

while(1){}

到主函数结束。

那么这里发生了什么?在释放所有 printf 函数的程序结束时是否会发生某种魔法?

如何在程序还在运行的时候让它 printf?

【问题讨论】:

  • printf 是缓冲输出,因此您应该在每次 printf 后关闭缓冲 (setbuf(stdout, NULL);) 或刷新 (fflush(stdout);)。

标签: c terminal printf termios


【解决方案1】:

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

尝试使用setvbuf 禁用缓冲。

要完全禁用标准输出上的缓冲:

setvbuf(stdout, (char *)NULL, _IONBF, 0); 

为每一行启用缓冲:

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

【讨论】:

  • 工作就像一个魅力!感谢您的帮助!
猜你喜欢
  • 2022-01-22
  • 1970-01-01
  • 2014-03-09
  • 2019-04-15
  • 2016-01-09
  • 2016-07-15
相关资源
最近更新 更多