如何在循环中连续打印变量,并在Linux下用C命中一个转义键终止?

Sil*_*Cat 5 c linux loops nonblocking getchar

请在下面找到代码部分.我想在循环中连续打印变量的当前值.一旦我按下转义键,就必须终止循环.这里的问题是执行在getchar函数处停止.但我希望它继续并打印变量的值,直到我点击退出按钮.

do
{
     vUpdateVariable();        // routine to update the current value of variable
     printf("Value is %f\r", fVariable); 
     ucKey = getchar();
     usleep(1000);
}while (ucKey != 0x1B);  
Run Code Online (Sandbox Code Playgroud)

Sil*_*Cat 0

我用下面的代码让它工作了。用于连续打印变量。必须使用 stderr。当程序员明确要求时,stdout 将刷新缓冲区,或者当最方便时,stderr 立即写入消息。由于您的终端的规范模式,您需要按 Enter 确认您的用户输入。必须禁用规范模式才能非阻塞执行代码。规范模式意味着它总是等待 Enter 来确认用户输入。如果这不是你的情况,nonblock 是一个可以满足这种情况的函数。我自己也想不通。从其他论坛获取代码和解释。

#include<stdio.h>
#include<curses.h>
#include<unistd.h>
#include <termios.h>
#include <sys/time.h>

#define NB_ENABLE 0x01
#define NB_DISABLE 0x00

int kbhit()
{
    struct timeval tv;
    fd_set fds;
    tv.tv_sec = 0;
    tv.tv_usec = 0;
    FD_ZERO(&fds);
    FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0
    select(STDIN_FILENO+1, &fds, NULL, NULL, &tv);
    return FD_ISSET(STDIN_FILENO, &fds);
}

void nonblock(int state)
{
     struct termios ttystate;
     tcgetattr(STDIN_FILENO, &ttystate); //get the terminal state

     if (state==NB_ENABLE)
     {
          //turn off canonical mode
          ttystate.c_lflag &= ~ICANON;
          //minimum of number input read.
          ttystate.c_cc[VMIN] = 1;
     }
     else if (state==NB_DISABLE)
     {
           //turn on canonical mode
          ttystate.c_lflag |= ICANON;
     }
     //set the terminal attributes.
     tcsetattr(STDIN_FILENO, TCSANOW, &ttystate);
 }
 int main()
 {
      char c,i;
      while(c != 27)
      {
           usleep(10000);
           vUpdateVariable();        // routine to update the current value of variable
           printf(stderr,"Value is %f\r", fVariable);            
           i=kbhit();
           c=fgetc(stdin);
       }
       nonblock(NB_DISABLE);
       return 0;
 }
Run Code Online (Sandbox Code Playgroud)