Pergunta

I'm using Lubuntu with LXterminal.

I have (somewhat) unashamedly copied the basis for this code from a stack overflow answer that gives details on c non-blocking keyboard input.

This is the first part:

#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;
    }
}

Here is one main function that shows some strange behavior.

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");

}

What this main loop does is it gets 6 character blocks (ex. ENTER 6 times or arrow key twice.) However, where it says printf there is no printout until the program finishes.

This can be seen better when you add

while(1){}

to the end of the main function.

So what's going on here? Is there some sort of magic that happens at the end of the program that releases all of the printf functions?

How do I make it printf when the program is still running?

Foi útil?

Solução

Apparently, you are victim of excessive buffering.

Try to disable buffering using setvbuf.

To completely disable buffering on stdout:

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

To enable buffering for each line:

setvbuf(stdout, (char *)NULL, _IOLBF, 0); 
// or
setlinebuf(stdout); 
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top