Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15456045
  • 博文数量: 2005
  • 博客积分: 11986
  • 博客等级: 上将
  • 技术积分: 22535
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-17 13:56
文章分类

全部博文(2005)

文章存档

2014年(2)

2013年(2)

2012年(16)

2011年(66)

2010年(368)

2009年(743)

2008年(491)

2007年(317)

分类:

2009-11-05 21:34:50

《linux下使用poll读取terminal终端上等待回车后送入的一行字符串》
/*
 * Copyright (c) 2009 Luther Ge
 */
#include
#include
static struct termios tio_orig;

int main(void)
{
    char buf[10];

    struct termios tio_new;
    tcgetattr(0,&tio_orig);
    tio_new=tio_orig;
    tio_new.c_lflag &= ~(ICANON|ECHO); /* Clear ICANON and ECHO. */
    tio_new.c_cc[VMIN] = 1;
    tio_new.c_cc[VTIME] = 0;
    tcsetattr(0,TCSANOW,&tio_new);

    int retval = read(0, buf, 1);
    if (retval <= 0)
        fprintf(stderr, "[luther.gliethttp] : error\n");
    else fprintf(stderr, "[luther.gliethttp] : %c\n", buf[0]);
    
    tcsetattr(0,TCSANOW,&tio_orig);
}
使用poll机制1
/*
 * Copyright (c) 2009 Luther Ge
 */
#include
#include
#include
#include
static struct termios tio_orig;

int main(void)
{
    struct pollfd pfds;
    char buf[10];

    struct termios tio_new;
    tcgetattr(0, &tio_orig);
    tio_new = tio_orig;
    tio_new.c_lflag &= ~(ICANON|ECHO); /* Clear ICANON and ECHO. */
    tio_new.c_cc[VMIN] = 1;
    tio_new.c_cc[VTIME] = 0;
    tcsetattr(0, TCSANOW, &tio_new);

    memset(&pfds, 0, sizeof(pfds));
    pfds.fd = 0;
    pfds.events = POLLIN;

    poll(&pfds, 1, 2*1000);

    if (pfds.revents & POLLIN) {
        read(0, buf, 1);
        tcflush(0, TCIFLUSH);  // [luther.gelitthtp]清空stdin输入的多余其他数据
        printf("=========[luther.gliethttp]=========\ninput char is : %c\n", buf[0]);
    }

    tcsetattr(0,TCSANOW,&tio_orig);
    return 0;
}
使用poll机制2

/*
 * Copyright (c) 2009 Luther Ge
 */
#include
#include
#include
#include
static struct termios tio_orig;

int main(void)
{
    struct pollfd pfds;
    char buf[10];

    struct termios tio_new;
    tcgetattr(0, &tio_orig);
    tio_new = tio_orig;
    tio_new.c_lflag &= ~(ICANON|ECHO); /* Clear ICANON and ECHO. */
    tio_new.c_cc[VMIN] = 1;
    tio_new.c_cc[VTIME] = 0;
    tcsetattr(0, TCSANOW, &tio_new);

    memset(&pfds, 0, sizeof(pfds));
    pfds.fd = 0;
    pfds.events = POLLIN;

    for (;;) {
        poll(&pfds, 1, 0);

        if (pfds.revents & POLLIN) {
            read(0, buf, 1);
            tcflush(0, TCIFLUSH);  // [luther.gelitthtp]清空stdin输入的多余其他数据
            printf("=========[luther.gliethttp]=========\ninput char is : %c\n", buf[0]);
        }
        usleep(100*1000);
    }

    tcsetattr(0,TCSANOW,&tio_orig);
    return 0;
}



阅读(2696) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~