首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C termios和printf问题

C termios和printf问题
EN

Stack Overflow用户
提问于 2013-05-26 20:42:02
回答 1查看 1.2K关注 0票数 1

我和LXterminal一起使用Lubuntu。

我(在某种程度上)无耻地从一个给出c非阻塞键盘输入细节的stack overflow answer中复制了这段代码的基础。

这是第一部分:

代码语言:javascript
复制
#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;
    }
}

这里有一个函数,它显示了一些奇怪的行为。

代码语言:javascript
复制
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的地方,在程序完成之前没有打印输出。

当您添加

代码语言:javascript
复制
while(1){}

主要功能的结束。

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-26 20:52:47

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

尝试使用setvbuf禁用缓冲。

要完全禁用stdout上的缓冲:

代码语言:javascript
复制
setvbuf(stdout, (char *)NULL, _IONBF, 0); 

要为每一行启用缓冲:

代码语言:javascript
复制
setvbuf(stdout, (char *)NULL, _IOLBF, 0); 
// or
setlinebuf(stdout); 
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16763519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档