For Programmers: Free Programming Magazines  


Home > Archive > Unix Programming > September 2006 > Re: Getting input and supporting timeout









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: Getting input and supporting timeout
Andre

2006-09-11, 7:00 pm

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


Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com