【问题标题】:How to handle key pressed in a Linux console in C?如何在 C 中处理 Linux 控制台中按下的键?
【发布时间】:2011-02-28 09:12:54
【问题描述】:

我正在使用 Linux 控制台,我想做一个在按下 ESC 之前输出随机字符的程序。如何制作这样的键盘处理程序?

【问题讨论】:

标签: c linux keyboard


【解决方案1】:

默认情况下,终端设备的线路规则通常在规范模式下工作。在这种模式下,终端驱动程序不会将缓冲区呈现给用户空间,直到看到换行符(按下 Enter 键)。

您可以使用@987654321@ 操作termios 结构,将终端设置为原始(非规范)模式。分别清除ECHOICANON 标志会在键入字符时禁用回显字符,并导致直接从输入队列中满足读取请求。在c_cc 数组中将VTIMEVMIN 的值设置为零会导致读取请求(fgetc())立即返回而不是阻塞;有效地轮询标准输入。如果字符在流中不可用,则对 fgetc() 的调用将返回 EOF

#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <time.h>

int getkey() {
    int character;
    struct termios orig_term_attr;
    struct termios new_term_attr;

    /* set the terminal to raw mode */
    tcgetattr(fileno(stdin), &orig_term_attr);
    memcpy(&new_term_attr, &orig_term_attr, sizeof(struct termios));
    new_term_attr.c_lflag &= ~(ECHO|ICANON);
    new_term_attr.c_cc[VTIME] = 0;
    new_term_attr.c_cc[VMIN] = 0;
    tcsetattr(fileno(stdin), TCSANOW, &new_term_attr);

    /* read a character from the stdin stream without blocking */
    /*   returns EOF (-1) if no character is available */
    character = fgetc(stdin);

    /* restore the original terminal attributes */
    tcsetattr(fileno(stdin), TCSANOW, &orig_term_attr);

    return character;
}

int main()
{
    int key;

    /* initialize the random number generator */
    srand(time(NULL));

    for (;;) {
        key = getkey();
        /* terminate loop on ESC (0x1B) or Ctrl-D (0x04) on STDIN */
        if (key == 0x1B || key == 0x04) {
            break;
        }
        else {
            /* print random ASCII character between 0x20 - 0x7F */
            key = (rand() % 0x7F);
            printf("%c", ((key < 0x20) ? (key + 0x20) : key));
        }
    }

    return 0;
}

注意:为简单起见,此代码省略了错误检查。

【讨论】:

  • 这似乎有效,但似乎每次都提供整个缓冲区。因此,如果我按 a 然后 b 然后 c,按 c 后它显示 aababc
  • @Jackie 可能在character = fgetc(stdin); 之后做一个while (getchar() != EOF);
  • 非常感谢您的简洁回答!
【解决方案2】:

一键更改 tty 设置:

int getch(void) {
      int c=0;

      struct termios org_opts, new_opts;
      int res=0;
          //-----  store old settings -----------
      res=tcgetattr(STDIN_FILENO, &org_opts);
      assert(res==0);
          //---- set new terminal parms --------
      memcpy(&new_opts, &org_opts, sizeof(new_opts));
      new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);
      tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);
      c=getchar();
          //------  restore old settings ---------
      res=tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);
      assert(res==0);
      return(c);
}

【讨论】:

  • ICRNL 不进入 c_iflag 字段,而不是 c_lflag 字段?
【解决方案3】:

getch() 可能来自 Curses 库?此外,您需要使用 notimeout() 告诉 getch() 不要等待下一次按键。

【讨论】:

  • 你应该明确提到你在谈论 (N)curses 库。
  • 注意:来自 ncurses 的 getch() 需要初始化适当的 ncurses “屏幕”,否则它将无法工作。
  • 您还必须初始化库 - 这是 @ShinTakezou 所说的变体。
【解决方案4】:
#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <signal.h>

char * me = "Parent";

void sigkill(int signum)
{
    //printf("=== %s EXIT SIGNAL %d ===\n", me, signum);
    exit(0);
}

main()
{
    int pid = fork();
    signal(SIGINT, sigkill);
    signal(SIGQUIT, sigkill);
    signal(SIGTERM, sigkill);
    if(pid == 0) //IF CHILD
    {  
        int ch;
        me = "Child";
        while(1)
        {  
            ch = (rand() % 26) + 'A';   // limit range to ascii A-Z
            printf("%c",ch);
            fflush(stdout); // flush output buffer
            sleep(2);   // don't overwhelm
            if (1 == getppid())
            {  
                printf("=== CHILD EXIT SINCE PARENT DIED ===\n");
                exit(0);
            }
        }
        printf("==CHILD EXIT NORMAL==\n");
    }
    else //PARENT PROCESS
    {  
        int ch;
        if((ch = getchar())==27)
            kill(pid, SIGINT);
        //printf("==PARENT EXIT NORMAL (ch=%d)==\n", ch);
    }
    return(0);
}

在这个程序中你只需要在esc 字符之后按enter,因为getchar()是一个阻塞函数。 您也可以根据需要删除或减少子进程的睡眠时间。

【讨论】:

  • 除了getchar等待输入,所以getchar等待用户按[回车]时不会输出随机字符。
猜你喜欢
  • 2010-11-27
  • 1970-01-01
  • 2010-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多