歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux中實現對輸入的異步

Linux中實現對輸入的異步

日期:2017/3/1 9:41:28   编辑: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()

更多詳情見請繼續閱讀下一頁的精彩內容: http://www.linuxidc.com/Linux/2014-08/105005p2.htm

Copyright © Linux教程網 All Rights Reserved