home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / unix / bsd / 11161 < prev    next >
Encoding:
Text File  |  1993-01-12  |  2.1 KB  |  58 lines

  1. Newsgroups: comp.unix.bsd
  2. Path: sparky!uunet!mcsun!sunic!kth.se!news.kth.se!olof
  3. From: olof@ikaros.fysik4.kth.se (Olof Franksson)
  4. Subject: Re: a unix terminal question
  5. In-Reply-To: dps@delhi.esd.sgi.com's message of 11 Jan 93 22:48:02 GMT
  6. Message-ID: <OLOF.93Jan12134356@ikaros.fysik4.kth.se>
  7. Sender: usenet@kth.se (Usenet)
  8. Nntp-Posting-Host: ikaros.fysik4.kth.se
  9. Organization: Physics IV, Royal Institute of Technology, S-100 44 Stockholm,
  10.     Sweden
  11. References: <1iql6kINNisk@ub.d.umn.edu>
  12.     <1993Jan11.215312.2080@fcom.cc.utah.edu> <uonuhjc@zola.esd.sgi.com>
  13. Date: Tue, 12 Jan 1993 12:43:56 GMT
  14. Lines: 42
  15.  
  16.    > In article <1iql6kINNisk@ub.d.umn.edu> cbusch@ub.d.umn.edu (Chris) writes:
  17.    > >
  18.    > >   How does one read in a character from standard input without having
  19.    > >the program wait for the key.  Basically, I want to do something like:
  20.    > >    if(kbhit()) c=getch();
  21.    > >Except that is not standard, and I want it to work on all platforms.
  22.    > 
  23.    > This is a bad thing to do, unless you have processing to do when characters
  24.    > aren't present, and you do your checks relatively infrequently compared to
  25.    > the procesing itself; otherwise, you will be in a buzz-loop and suck your
  26.    > CPU through the floor.  This is common practice under DOS where there is
  27.    > nothing else running, but is a generally bad thing to do.
  28.    >
  29.    > The CORRECT way to do this:  use the select() or poll() system call to
  30.    > wait for an interval or a character to be present.  Resoloution is
  31.  
  32. IF one would like to read from a tty in the manner described in
  33. the question from cbusch@ub.d.umn.edu, the fcntl()-call might be
  34. used. The following short example print *-characters with 0-1s
  35. intervalls on standard output until a character appears on standard
  36. input, or 20 *-characters have been printed.
  37.  
  38. #include <fcntl.h>
  39.  
  40. main()
  41. {
  42.   int ret, fflag, nfflag, i;
  43.   
  44.   fflag = fcntl(0, F_GETFL, 0);           /* No wait for char input */
  45.   nfflag = fflag | O_NDELAY;
  46.   nfflag = fcntl(0, F_SETFL, nfflag);
  47.  
  48.   putchar('*');
  49.   for (i = 0; i < 20 && (ret = getchar()) == -1; i++) {
  50.     putchar('*');
  51.     sleep(1);
  52.   }
  53.  
  54.   fcntl(0, F_SETFL, fflag);
  55.   putchar('\n');
  56. }
  57.  
  58.