473,725 Members | 2,118 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Linux: Unbuffered reading from stdin

Hi folks.

I'm somewhat new to *nix programming and just ran into a problem. I have
to take user input from the terminal but like to constrain that to some
rules given, i.e. "numbers only" or "alphanumer ic only" etc.
scanf would do, but I don't like the fact that wrong ('disallowed')
characters are visible and all that stuff. For that I need unbuffered
input. Since there seems to be no atomic function to do that I tried to
fiddle around with ioctl() and that seems to work fine. Currently I flag
out ICANON and ECHO from the tty descriptor, set a minimum input of 1
byte, getch() or read() a byte, check, printf(), fine.
However things become nasty when the user presses an key that sends an
escape sequence. I've seen some code on the web that does the following
approach: Check for character==27. If so, read() 4 bytes into a buffer,
zero terminate the buffer accordingly then strcmp() the buffer against
the actual escape sequences.

But then there are two problems:

1) The escape sequences seem to change with every terminal type. On my
terminal the codes for F1 to F5 are ^OP, ^OQ, ^OR, ^OS, ^[15~ (etc)
while on the code given in the web they used to be [[A, [[B etc.
Are there some defines?

2) What happens when the user presses just ESC? Sounds easy to me, just
check if there are no more chars in stdin - but how do you do that? By
just read()ing STDIN_FILENO after an ESC the terminal is blocked until
another key is pressed - that is not really what I want.

Any ideas? Or am I reinventing the wheel?
Regards,
Markus
Oct 22 '07 #1
7 6152
Markus Mayer wrote:
Hi folks.

I'm somewhat new to *nix programming and just ran into a problem. I have
to take user input from the terminal but like to constrain that to some
rules given, i.e. "numbers only" or "alphanumer ic only" etc.
scanf would do, but I don't like the fact that wrong ('disallowed')
characters are visible and all that stuff. For that I need unbuffered
input.
However things become nasty when the user presses an key that sends an
escape sequence.
Any ideas? Or am I reinventing the wheel?
This is really a comp.unix.progr amming question, but it
sounds like ncurses is what you want.

--
imalone
Oct 22 '07 #2
Am 22.10.2007 13:24 postulierte Markus Mayer folgendes:
[...]
2) What happens when the user presses just ESC? Sounds easy to me, just
check if there are no more chars in stdin - but how do you do that? By
just read()ing STDIN_FILENO after an ESC the terminal is blocked until
another key is pressed - that is not really what I want.
D'oh ... that was a dumb one. By reading a maximum of n bytes into the
buffer I can check bytes 2..n if buffer[0] is 27. Okay - done.

Are there other solutions though?

Regards,
Markus
Oct 22 '07 #3
Am 22.10.2007 13:38 postulierte Ian Malone folgendes:
Markus Mayer wrote:
>Hi folks.

I'm somewhat new to *nix programming and just ran into a problem. I have
to take user input from the terminal but like to constrain that to some
rules given, i.e. "numbers only" or "alphanumer ic only" etc.
scanf would do, but I don't like the fact that wrong ('disallowed')
characters are visible and all that stuff. For that I need unbuffered
input.
>However things become nasty when the user presses an key that sends an
escape sequence.

This is really a comp.unix.progr amming question, but it
sounds like ncurses is what you want.
Haven't seen that group, thanks! I'll have a deeper look at ncurses, but
from what I've see so far I think that I'm not allowed to use it; I
really have to do it 'on my own'. :/

Thanks anyway!
Markus
Oct 22 '07 #4
Markus Mayer wrote:

<about handling escape sequences and special characters in unbuffered
input>

Just use ncurses and ask in a UNIX group like
<news:comp.unix .programming>

Oct 22 '07 #5
Op Mon, 22 Oct 2007 18:26:28 +0530 schreef santosh:
Markus Mayer wrote:

<about handling escape sequences and special characters in unbuffered
input>

Just use ncurses and ask in a UNIX group like
<news:comp.unix .programming>
<news:comp.unix .programmer>
--
Coos
Oct 22 '07 #6
Ian Malone wrote:
Markus Mayer wrote:
>I'm somewhat new to *nix programming and just ran into a problem.
I have to take user input from the terminal but like to constrain
that to some rules given, i.e. "numbers only" or "alphanumer ic
only" etc. scanf would do, but I don't like the fact that wrong
('disallowed ') characters are visible and all that stuff. For
that I need unbuffered input.

However things become nasty when the user presses an key that
sends an escape sequence.

Any ideas? Or am I reinventing the wheel?

This is really a comp.unix.progr amming question, but it
sounds like ncurses is what you want.
No, he needs getc and ungetc. A simple routine can input numbers
from a stream with that, and ensure the terminating (non-numeric)
character is left in the stream.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Oct 23 '07 #7
#if offtopic == pet_peeve

On Mon, 22 Oct 2007 13:24:49 +0200, Markus Mayer
<co************ ***********@def x.dewrote:
I'm somewhat new to *nix programming and just ran into a problem. I have
to take user input from the terminal but like to constrain that to some
rules given, i.e. "numbers only" or "alphanumer ic only" etc.
scanf would do, but I don't like the fact that wrong ('disallowed')
characters are visible and all that stuff. For that I need <snip>
Aside: Personally I don't share your goal. I would rather _see_ what I
entered -- with any retained invisible bits made visible, e.g. caret,X
for control-X -- plus a statement of why it's wrong and/or what would
be permitted. The allegedly user-friendly interface in my experience
seems to encourage the approach of 'oh, just push keys (or click) at
random until something happens that appears more or less right'. But
this is personal taste; I don't mind _you_ wanting it the other way.
However things become nasty when the user presses an key that sends an
escape sequence. I've seen some code on the web that does the following
approach: Check for character==27. If so, read() 4 bytes into a buffer,
zero terminate the buffer accordingly then strcmp() the buffer against
the actual escape sequences.

But then there are two problems:

1) The escape sequences seem to change with every terminal type. On my
terminal the codes for F1 to F5 are ^OP, ^OQ, ^OR, ^OS, ^[15~ (etc)
while on the code given in the web they used to be [[A, [[B etc.
Are there some defines?
Not really. Although I'm a bit surprised you can still find today many
different real terminals or even emulators, there used to be a huge
variety. There are some standards, notably ANSI X3.64 (I suppose now
INCITS 64), which was used on a large scale by DEC's VT100 and VT200
series and by the now prevalent Xwindows utility xterm. But even that
standard has portions that may be varied by each implementor/ation.

This is precisely why vanilla Unix tty drivers don't even try to deal
with it; they only support sequential, across-and-down-the-page,
printable plus CR LF/NL, probably BS, and maybe HT. And similarly
TELNET the protocol goes very little beyond this (although specific
TELNET _clients_ may do more), and also the CCITT equivalent X.3 if
you can find anyone who even knows of it much less uses it.
2) What happens when the user presses just ESC? Sounds easy to me, just
check if there are no more chars in stdin - but how do you do that? By
just read()ing STDIN_FILENO after an ESC the terminal is blocked until
another key is pressed - that is not really what I want.
The conventional approach is a short timeout, which in Unix would be
poll, select, or similar probably combined with nonblocking I/O.
But if your transmission path is anything more complicated than an
actual hardwired RS232 cable (which is limited to 50ft; well, or
RS42x/385IIRC up to maybe a thousand feet) then occasionally you will
get delays introduced to the middle of your input stream due to
encoding, routing, retransmission, congestion, or whatever and your
code will, like the villain in Indiana Jones (3?), 'choose badly'.
When this happens, the program and the terminal get out of sync, and
unless the user recognizes it quickly AND the program provides a way
to recover (such as vi ^L 're-draw') it can lead to corrupted files
and databases and even things like unintended stock trades.

The other alternative is just have people not use the ESC key. Some
people, or more commonly their organizations, used to physically
remove or block the ESC key on real physical terminals dedicated to an
application/system. Nowadays if you're using the same PC for your
terminal emulator and for other tasks you probably can't allow that.
Any ideas? Or am I reinventing the wheel?
Yes. As others have noted, the most widespread and established
solution for this, and probably most convenient for you, is (are?) the
various variants of curses/ncurses. There were plenty of other
attempts, although the ones I knew of were mostly tied to particular
systems or applications or both; but if you're interested I warn you
this can be a giant time sink -- in the '70s and into the '80s, there
were quite a few people whose fulltime job, or a major chunk of it,
was keeping track of and coping with different 'smart' terminal types
and in particular their protocols. The folks on alt.folklore.co mputers
probably can help you, but it's such hightraffic I don't have time to
follow it myself except for occasional crossposts.

#endif
- formerly david.thompson1 || achar(64) || worldnet.att.ne t
Nov 4 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
6148
by: Max Rabkin | last post by:
While java's System.in is, according to the javadocs, an InputStream, it is in fact an instance of java.io.BufferedInputStream. Is there any way to have unbuffered access to it without hacking the JRE? (I can do it on my own computer, simply changing FilterInputStream's "in" field from "protected" to "public", but then I can't distribute my program). --Max
5
17422
by: richard | last post by:
I have a simple test to pass information from a client to a server using named pipe. what I really want is: when I type a line on the client, the server will output the line immediately. but to my surprise, I always have to terminate the client to get the server in action, i.e. prints out what I typed. anything I missed? I am compiling using gcc without any option. thanks, ---RICH
11
3249
by: Lonnie Princehouse | last post by:
>From the cmd shell on both Windows 2k and XP, I'm getting this weird syntax error in conjunction with the unbuffered flag. It works fine without -u. Has anyone else encountered it? This didn't happen with Python 2.2... C:\>python -u Python 2.4.1 (#65, Mar 30 2005, 09:13:57) on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print 'hello'
6
2485
by: Charlie Zender | last post by:
Hi, I have a program which takes the output filename argument from stdin. Once the program knows the output filename, it tries to open it. If the output file exists, the program asks the user to confirm whether he really wants to overwrite the existing output file. The problem is that the second read from stdin, to obtain the user response whether to overwrite the existing output file, never waits for the user's response. It's as if a...
4
4194
by: pank7 | last post by:
hi everyone, I have a program here to test the file IO(actually output) with buffer turned on and off. What I want to see is that there will be obvious differece in time. Here I have an input file scales 1.1M, what I did is just copy it to another output file(ten times). But I don't think I see any difference. My file system is ext3, with debian sarge(kernel-2.6.8). Here is the main part of my program:
19
5384
by: Lee Crabtree | last post by:
Is there a class in the framework that allows me read text from a file in an unbuffered manner? That is, I'd like to be able to read lines in the same manner as StreamReader.ReadLine(), but I also need to be able to accurately get the position in the file of that line. Since StreamReader and FileStream both buffer data, you can't equate the BaseStream.Position with the data you're reading from the stream. Lee Crabtree
0
1209
by: Hamish Allan | last post by:
Hi, The man page for python says: "-u Force stdin, stdout and stderr to be totally unbuffered." However, when I try: $ ssh localhost python -u print 'hello, world'
3
11259
by: Paddy | last post by:
Hi, I am am falling at the first hurdle when trying to access a library using ctypes. I have a file libucdb.so which the file command says is shared object, but I cannot get it to load: Any help would be appreciated: dmccarthy: file /opt/questasim_6.4/questasim/linux/libucdb.a /opt/
27
3156
by: =?ISO-8859-1?Q?Tom=E1s_=D3_h=C9ilidhe?= | last post by:
I have a fully-portable C program (or at least I think I do). It works fine on Windows, but malfunctions on Linux. I suspect that there's something I don't know about the standard input stream that's causing the problem. Here's how I wrote the program originally: #include <stdio.h> #include <string.h>
0
8888
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9176
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9113
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3221
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.