*BSD News Article 9774


Return to BSD News archive

Received: by minnie.vk1xwt.ampr.org with NNTP
	id AA6478 ; Sun, 10 Jan 93 01:05:01 EST
Newsgroups: comp.unix.bsd
Path: sserve!manuel.anu.edu.au!munnari.oz.au!uunet!mcsun!sunic!kth.se!news.kth.se!olof
From: olof@ikaros.fysik4.kth.se (Olof Franksson)
Subject: Re: a unix terminal question
In-Reply-To: dps@delhi.esd.sgi.com's message of 11 Jan 93 22:48:02 GMT
Message-ID: <OLOF.93Jan12134356@ikaros.fysik4.kth.se>
Sender: usenet@kth.se (Usenet)
Nntp-Posting-Host: ikaros.fysik4.kth.se
Organization: Physics IV, Royal Institute of Technology, S-100 44 Stockholm,
	Sweden
References: <1iql6kINNisk@ub.d.umn.edu>
	<1993Jan11.215312.2080@fcom.cc.utah.edu> <uonuhjc@zola.esd.sgi.com>
Date: Tue, 12 Jan 1993 12:43:56 GMT
Lines: 42

   > In article <1iql6kINNisk@ub.d.umn.edu> cbusch@ub.d.umn.edu (Chris) writes:
   > >
   > >   How does one read in a character from standard input without having
   > >the program wait for the key.  Basically, I want to do something like:
   > >    if(kbhit()) c=getch();
   > >Except that is not standard, and I want it to work on all platforms.
   > 
   > This is a bad thing to do, unless you have processing to do when characters
   > aren't present, and you do your checks relatively infrequently compared to
   > the procesing itself; otherwise, you will be in a buzz-loop and suck your
   > CPU through the floor.  This is common practice under DOS where there is
   > nothing else running, but is a generally bad thing to do.
   >
   > The CORRECT way to do this:  use the select() or poll() system call to
   > wait for an interval or a character to be present.  Resoloution is

IF one would like to read from a tty in the manner described in
the question from cbusch@ub.d.umn.edu, the fcntl()-call might be
used. The following short example print *-characters with 0-1s
intervalls on standard output until a character appears on standard
input, or 20 *-characters have been printed.

#include <fcntl.h>

main()
{
  int ret, fflag, nfflag, i;
  
  fflag = fcntl(0, F_GETFL, 0);           /* No wait for char input */
  nfflag = fflag | O_NDELAY;
  nfflag = fcntl(0, F_SETFL, nfflag);

  putchar('*');
  for (i = 0; i < 20 && (ret = getchar()) == -1; i++) {
    putchar('*');
    sleep(1);
  }

  fcntl(0, F_SETFL, fflag);
  putchar('\n');
}