1

LXterminal で Lubuntu を使用しています。

このコードの基礎を (ある程度) 恥ずかしがらずに、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;
    }
}

これは、いくつかの奇妙な動作を示す主な関数の 1 つです。

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 回押すか、矢印キーを 2 回押す)。

これは、追加するとよくわかります

while(1){}

メイン関数の最後まで。

それで、ここで何が起こっているのですか?すべてのprintf関数を解放するプログラムの最後に起こる魔法のようなものはありますか?

プログラムがまだ実行されているときに printf にするにはどうすればよいですか?

4

1 に答える 1

2

どうやら、あなたは過剰なバッファリングの被害者です。

を使用してバッファリングを無効にしてみてくださいsetvbuf

stdout でのバッファリングを完全に無効にするには:

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

各行のバッファリングを有効にするには:

setvbuf(stdout, (char *)NULL, _IOLBF, 0); 
// or
setlinebuf(stdout); 
于 2013-05-26T20:52:47.010 に答える