单线程中实现while循环中检测按键退出

 

#include <stdio.h>
#include <unistd.h> 
#include <sys/stat.h>
#include <linux/fs.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <termios.h>
#include <sys/ioctl.h>

 

static struct termio term_orig;
static int kbdflgs;

int kbhit(void)
{
    struct timeval tv;
    struct termios old_termios, new_termios;
    int error;
    int count = 0;
    tcgetattr(0, &old_termios);
    new_termios = old_termios;
    new_termios.c_lflag &= ~ICANON;
    new_termios.c_lflag &= ~ECHO;
    new_termios.c_cc[VMIN] = 1;
    new_termios.c_cc[VTIME] = 0;
    error = tcsetattr(0, TCSANOW, &new_termios);
    tv.tv_sec = 0;
    tv.tv_usec = 100;
    select(1, NULL, NULL, NULL, &tv);
    error += ioctl(0, FIONREAD, &count);
    error += tcsetattr(0, TCSANOW, &old_termios);
    return error == 0 ? count : -1;
}

/**
* system_mode
* reset the system to what it was before input_mode was
* called
*/
void system_mode(void)
{
    if (ioctl(0, TCSETA, &term_orig) == -1) {
        return;
    }
    fcntl(0, F_SETFL, kbdflgs);
}

/**
* input_mode
* set the system into raw mode for keyboard i/o
* returns  0 - error
*          1 - no error
*/
int input_mode(void)
{
    struct termio term;
    if (ioctl(0, TCGETA, &term) == -1) {
        return 0;
    }
   
    (void) ioctl(0, TCGETA, &term_orig);
    term.c_iflag = 0;
    term.c_oflag = 0;
    term.c_lflag = 0;
    term.c_cc[VMIN] = 1;
    term.c_cc[VTIME] = 0;
    if (ioctl(0, TCSETA, &term) == -1) {
        return 0;
    }
    kbdflgs = fcntl(0, F_GETFL, 0);
    int flags = fcntl(0, F_GETFL);
    flags &= ~O_NDELAY;
    fcntl(0, F_SETFL, flags);
    return 1;
}

/**
* getch
* read a single character from the keyboard without echo
* returns: the keypress character
*/
int getch(void)
{
    unsigned char ch;
    input_mode();
    while(read(0, &ch, 1) != 1);
    system_mode();
    return (ch);
}

 

int main(){

 while(1){

   //if 's' or 'S' pressed,exit while loop,
   if(kbhit()){
    char tmp = getch();
    if((tmp== 'S')||(tmp=='s'))
     break;
   }

  // continue doing some thing if no 'S' or 's' pressed

  ...............

 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值