Linux中实现对输入的异步


1:传统的输入信号

传统的输入都是通过阻塞来实现,例如getchar一直等待用户输入。又或者是再curses库中的getch都是通过阻塞的方式来等待用户输入。那么想象一个场景要设计一个游戏,这个游戏可以让玩家动态输入一些值来动态调整游戏参数。不可能通过getchar这样的阻塞函数来获取用户输入把。那么这个该如何实现呢,再想象一下另外一种场景操作系统的CPU不可能是一直等待网卡的输入把。所以对于一些特别的场景阻塞输入是无法满足要求的。下面的这个例子就是一个阻塞输入的例子。

#include<stdio.h>

#include<stdlib.h>

#include<curses.h>

 

void init_setup (  );

void init_end (  );

void on_input (  );

void do_main (  );

int main ( int argc, char *argv[] )

{

 

        init_setup();

        on_input();

        do_main();

        init_end();

        return EXIT_SUCCESS;

}

        /* ----------  end of function main  ---------- */

 

 

 

void init_setup (  )

{

        initscr();

        crmode();

        noecho();

        clear();

}              /* -----  end of function init_setup  ----- */

 

void init_end (  )

{

        endwin();

}              /* -----  end of function init_end  ----- */

 

void on_input (  )

{

        char c;

        while((c = getch()) != 'q'){

                if(c == 'w')

                mvaddch(20,20,'!');

                else if(c == 'e')

                mvaddch(20,20,'0');

                else if(c == 'r')

                mvaddch(20,20,'t');

        }

}              /* -----  end of function on_input  ----- */

 

void do_main (  )

{

        while(1){

                move(50,50);

                addstr("do other thing");

        }

 

}              /* -----  end of function do_main  ----- */


    从这个例子可以发现do_main没有执行,因为on_input一直等待用户输入阻塞了下面的程序运行。所以在有些场景像getchar或者getch这类的阻塞函数无法满足一些需求,那么就需要使用异步IO。异步IO的实现有两种方法:

    1.设置输入O_ASYNC位


    2.使用aio_read()

更多详情见请继续阅读下一页的精彩内容:

  • 1
  • 2
  • 3
  • 下一页

相关内容