システムとその動作方法によっては、STDIN をファイル ハンドルとして select 関数を使用することができます。Select ステートメントの時間をゼロに設定して、ポーリングしてデータがあるかどうかを確認したり、待機する時間を設定したりできます。
あなたはリンクを見ることができますhttp://www.gnu.org/s/libc/manual/html_node/Waiting-for-I_002fO.htmlを参照して、ソケットで select ステートメントを使用する例を確認してください。
この例を変更して、STDIN をファイル記述子として使用するようにしました。この関数は、保留中の入力がない場合は 0 を返し、保留中の入力がある場合 (つまり、誰かが入力のキーボードでキーを押した場合) は 1 を返し、何らかのエラーが発生した場合は -1 を返します。
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
int waitForKBInput(unsigned int seconds)
{
/* File descriptor set on which to wait */
fd_set set;
/* time structure which indicate the amount of time to
wait. 0 will perform a poll */
struct timeval timeout;
/* Initialize the file descriptor set. */
FD_ZERO (&set);
/* Use the Standard Input as the descriptor on which
to wait */
FD_SET (STDIN, &set);
/* Initialize the timeout data structure. */
timeout.tv_sec = seconds;
timeout.tv_usec = 0;
/* select returns 0 if timeout, 1 if input available, -1 if error. */
/* and is only waiting on the input selection */
return select (FD_SETSIZE,
&set, NULL, NULL,
&timeout));
}
これを試してみたところ、SelectとSTDINの実装が異なるため、機能しませんでした(キーボード入力を検出するために他の手段を使用する必要がありました)。
Visual C/C++ の場合、読み取るキーボード入力があるかどうかを示す関数 kbhit を使用できます。