2011年3月19日土曜日

タイムアウト機能付のコンソール入力

タイムアウト機能付のコンソール入力例です。

シグナルハンドラとインターバルタイマによる sleep 関数の例を利用し、時間内に入力が得られなければタイムアウトします。

01#include <stdio.h>
02#include <string.h>
03#include <unistd.h>
04#include <signal.h>
05#include <time.h>
06#include <sys/time.h>
07  
08//-----------------------------------------------------------------
09char* mygetchar(int timeout);
10//-----------------------------------------------------------------
11  
12int main()
13{
14    char* buf = mygetchar(5); // 5秒でタイムアウト
15    printf("input char: %s\n",buf);
16    return 0;
17}
18  
19//-----------------------------------------------------------------
20// タイムアウト付き文字入力
21//-----------------------------------------------------------------
22void mywait(int no) { printf("timeout.\n"); }
23 
24char* mygetchar(int timeout)
25{
26    static char buf[256];
27    struct sigaction sa;
28    struct itimerval itimer;
29  
30    // シグナルハンドラの設定
31    memset(&sa,0,sizeof(struct sigaction));
32    sa.sa_handler = mywait;
33    //sa.sa_flags   = SA_RESTART; // if restart input
34    if ( sigaction(SIGALRM,&sa,NULL) != 0 ){
35        perror("sigaction");
36        return 0;
37    }
38    // タイマーの設定
39    itimer.it_value.tv_sec  = itimer.it_interval.tv_sec  = timeout; // sec
40    itimer.it_value.tv_usec = itimer.it_interval.tv_usec = 0; // micro sec
41    if ( setitimer(ITIMER_REAL,&itimer,NULL) < 0 ) {
42        perror("setitimer");
43        return 0;
44    }
45    fgets(buf,256,stdin);
46    return buf;
47}
実行結果
1% ./list_xxx
2timeout.
3input char:
4% ./list_xxx
5abcde
6input char: abcde
7%

0 件のコメント:

コメントを投稿