Cでnon-blocking IO

こんな感じにすればできるらしい。

#include <stdio.h>
#include <termios.h>
#include <fcntl.h>
#include <time.h>

int main(int argc, char const* argv[])
{
	struct termios save_settings;
	struct termios settings;
	char c;

	tcgetattr(0,&save_settings);
	settings = save_settings;

	settings.c_lflag &= ~(ECHO|ICANON);  /* 入力をエコーバックしない、バッファリングしない */
	settings.c_cc[VTIME] = 0;
	settings.c_cc[VMIN] = 1;
	tcsetattr(0,TCSANOW,&settings);
	fcntl(0,F_SETFL,O_NONBLOCK);				/* 標準入力からの読み込むときブロックしないようにする */

	while(1){
		printf("\033[02K");
		if((c = getchar()) == EOF){
			printf("\rNO_INPUT ");
		}else if (c == 'q'){
			break;
		}else{
			printf("\rINPUT -> %c ",c);
		}
		fflush(stdout);
		sleep(1);
	}

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

fnctl(0,F_SETFL,O_NONBLOCK); とすると例えばgetchar()の場合は読み込むものがなければEOFが返るようになります。
この例だとついでにエコーバックを無くして、バッファリングをしないようにしてます。
何もキーボードを押さなければ "NO_INPUT" 、何かキーを押すと "INPUT -> a" みたいに1秒おきに表示されます。


参考
http://www.adl.nii.ac.jp/~moro/unix-programmer/faq-j_4.html