|
| I ended up solving my problem. For the benefit of others:
void MyClass::GetLine( std::string & input, int maxlen )
{
char buf[maxlen + 1]; /* null byte at end */
char *ptr;
struct termios ts, ots;
int c;
int fd = STDIN_FILENO;
tcgetattr(fd, &ts); /* save tty state */
ots = ts; /* structure copy */
ts.c_lflag &= ~(ICANON);
tcsetattr(fd, TCSAFLUSH, &ts);
WaitForData();
if ( IsTimedOut() )
{
return;
}
ptr = buf;
while ((c = cin.get()) != EOF && c != '\n' && c != '\r')
{
if (ptr < &buf[maxlen])
{
*ptr++ = c;
}
WaitForData();
if ( IsTimedOut() )
{
return;
}
}
*ptr = 0; /* null terminate */
cout << '\n'; /* we echo a newline */
tcsetattr(fd, TCSAFLUSH, &ots); /* restore TTY state */
input.clear();
input.append(buf);
}
void MyClass::WaitForData()
{
int fd = STDIN_FILENO;
fd_set fds;
struct timeval tv;
int retVal = 0;
cout.flush();
do
{
tv.tv_sec = this->timeout;
tv.tv_usec = 0;
FD_ZERO( &fds );
FD_SET( STDIN_FILENO, &fds );
int result = select(fd + 1, &fds, NULL, NULL, &tv );
if ( result == 0 )
{
this->timedout = true;
break;
}
else if ( result > 0 && FD_ISSET(fd,&fds) )
{
break;
}
}
while ( true );
}
Andre wrote:
> Hi,
>
> I am trying to write a routine that will wait for input and timeout
> after a certain time, if no input is provided at any point in the entry
> (empty input and partly entered input). It also needs to allow for the
> empty line entry (no characters inputted, but enter pressed).
>
> So far I have been looking at a mixture of playing with the termios
> attributes and the select() routine, since I can't depend on a SIGALARM
> or another thread for the timeout. If it makes any difference I am
> using C++. So far I haven't got anything that works to my liking.
>
> Any ideas? I'll provide what have if necessary.
>
> Andre
|
|