You are not logged in.
Pages: 1
OK I'm trying to have a simple loop which keeps on printing each number from 1,2,... on a different line and it keeps on doing so until the user enters 'e'.
e.g
for(i=0;i<=9999999999;i++)
{
printf("%d\n",i);
}
It does not take any input from user and keeps on printing but as soon as user presses e the program exits.Any clue how to go about this.
Offline
There are multiple ways to go about it... One is to use ncurses, and set nodelay(),
which is essentially non-blocking mode for input, so you can then call getch() each
time through the loop and it'll either fail or return a key if one has been pressed...
You can do similar without the ncurses overhead by using tcsetattr() to turn off ICANON,
then set FD 0 to non-blocking mode, and just do a read()... Or, you can just use
select()/poll() to check stdin for readability every time through the loop, and just do a
read() if there's something there to read... Or, you could use fcntl(F_SETOWN) with
O_ASYNC and a SIGIO handler to asynchronously be notified about input ready to be
read from stdin... Or, you could create 2 threads: one spitting out the numbers non-stop,
and one blocked on input from stdin, waiting to see the "e"; and, when it sees it, it would
kill the other thread to stop it... Etc... Like I said, there are multiple approaches...
Offline
Well thanks for your your answer .I'm new with c.So it would be great if you could tell me about how to use the stdout/poll option ..
Offline
Well, here's a simple example using select(), since I'm far more comfortable with it
than poll(), and I'm not going to do ALL your work for you... ;-)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <termios.h>
#include <sys/select.h>
int main ()
{
int i;
char c;
fd_set fds;
struct timeval timeout;
struct termios old, new;
if (tcgetattr (STDIN_FILENO, &old)) {
perror ("Unable to read old terminal attributes");
return (-1);
}
memcpy (&new, &old, sizeof (struct termios));
new.c_lflag &= ~(ICANON | ECHO);
if (tcsetattr (STDIN_FILENO, 0, &new)) {
perror ("Unable to set new terminal attributes");
return (-1);
}
for (i = 0;; i++) {
printf ("%d\n", i);
FD_ZERO (&fds);
FD_SET (STDIN_FILENO, &fds);
memset (&timeout, '\0', sizeof (timeout));
if ((select (STDIN_FILENO + 1, &fds, NULL, NULL, &timeout) > 0) &&
(read (STDIN_FILENO, &c, 1) == 1)) {
if (c == 'e')
break;
else
printf ("Read (%c)\n", c);
}
}
tcsetattr (STDIN_FILENO, 0, &old);
return (0);
}
Offline
Pages: 1