The tty Interface An introduction to “systems programming” in the Linux environment

advertisement
The tty Interface
An introduction to
“systems programming”
in the Linux environment
The “login” program
• An important “interactive” application
• Illustrates a human-computer dialogue:
– Computer says: What’s your name?
– User replies: (typing in his/her username)
– Computer says: What’s your password?
– User replies: (typing in his/her password)
– Computer performs a “lookup” operation
– Computer replies: ok, access is allowed
(or alternatively: access is denied)
Login program-structure
main
obtain_input
process_data
print_output
We saw this same basic program-structure once before
(i.e., in our ‘manydots.s’ demo)
But ‘login’ needs a ‘tweak’
•
•
•
•
•
•
Login requires user to type a password
The password is supposed to be secret
But computer prints it onscreen (‘echo’)
Anyone passing by will know the secret!
How can we stop the ‘automatic echo’?
It is a “systems programming” problem
How does the ‘tty’ work?
SOFTWARE
application
User space
tty_driver
c_lflag
Kernel space
input handling
c_iflag
c_cc
output handling
c_oflag
terminal_driver
c_cflag
HARDWARE
TeleType displaY device
struct tty {
c_iflag;
c_oflag;
c_cflag;
c_lflag;
c_line;
c_cc[ ];
};
The ‘c_lflag’ field
•
•
•
•
•
•
It’s an array of flag-bits
Individual bits have symbolic names
Names conform to a POSIX standard
Linux names match other UNIX’s names
Though actual symbol-values may differ
Your C/C++ program should use:
#include <termios.h>
for portability to other UNIX environments
The ‘c_lflag’ field (continued)
• Symbolic names defined in a header-file
• Header-files are in ‘/usr/include’ directory
(and in its sub-directories)
• Important flag-bit names: ECHO, ECHONL
• You can search for them (by using ‘grep’):
– $ grep ECHO /usr/include/*.h
– $ grep ECHO /usr/include/*/*.h
• ECHO is in ‘/usr/include/asm/termbits.h’
How to turn off tty echo
• Two programming interface-functions:
– int tcgetattr( int fd, struct termios *tios );
– Int tcsetattr( int fd, int fl, struct termios *tios );
• Algorithm:
– Use ‘tcgetattr()’ to get current settings
– Clear the ECHO flag in c_lflag
– Set the ECHONL flag in c_lflag
– Use ‘tcsetattr()’ to install new settings
Demo ‘noecho.cpp’
•
•
•
•
High-level language: briefer and clearer
So we use C++ to demonstrate this idea
We worry later about assembly language
A minor side-issue: converting ascii codes
for letters from lowercase to uppercase
• Helps to know the C++ logic operators
AND, OR, XOR, NOT
• Important C++ operators: &, |, ^, and ~
• Needed often in systems programming
• Examples (used in ‘noecho.cpp’):
c_lflag &= ~ECHO;
c_lflag |= ECHONL;
• Useful also for converting letters from
lowercase to uppercase (or vice-versa)
Download