あなたはncursesを使用することができますか、このblog postで説明するように、あなたが選択し使用することができますしない場合。基本的には、select
を使用してタイムアウトを指定できます。 stdin FDが設定されている場合は、それを安全に読み取ることができ、ブロックされません。選択についての詳細は、this outともちろんWikipediaをチェックしてください。それは知るための便利な呼び出しです。例えば、
// if != 0, then there is data to be read on stdin
int kbhit()
{
// timeout structure passed into select
struct timeval tv;
// fd_set passed into select
fd_set fds;
// Set up the timeout. here we can wait for 1 second
tv.tv_sec = 1;
tv.tv_usec = 0;
// Zero out the fd_set - make sure it's pristine
FD_ZERO(&fds);
// Set the FD that we want to read
FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0
// select takes the last file descriptor value + 1 in the fdset to check,
// the fdset for reads, writes, and errors. We are only passing in reads.
// the last parameter is the timeout. select will return if an FD is ready or
// the timeout has occurred
select(STDIN_FILENO+1, &fds, NULL, NULL, &tv);
// return 0 if STDIN is not ready to be read.
return FD_ISSET(STDIN_FILENO, &fds);
}
もスレッドがこのためにやり過ぎであるPeek stdin using pthreads
では、新しいスレッドで入力を読み込み、その後、10秒経過した後にメインスレッドからそのスレッドを殺すことはできますか? – GWW
@ GWWの提案以外に、低レベルのOS機能をいつでも使用できます。 Linux/* nixでは、これを "生の" I/Oと呼びます。しかし、私はそれ以来長い時間がかかりました。 –