Terminal Control operating systems. Terminal Control may seem like an arcane subject, but … It illustrates the relationship between devices and files.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

Linux Serial Programming for POSIX Operating Systems
Lab 9 CIS 370 Umass Dartmouth.  A pipe is typically used as a one-way communications channel which couples one related process to another.  UNIX deals.
DOS and BIOS Interrupts DOS and BIOS interrupts are used to perform some very useful functions, such as displaying data to the monitor, reading data from.
Programming In C++ Spring Semester 2013 Lecture 8 Programming In C++, Lecture 8 By Umer Rana.
Terminal I/O POSIX termios Two terminal I/O modes Canonical and non-canonical Getting and setting terminal attributes Terminal window size: struct winsize.
Daemon Processes Long lived utility processes Often started at system boot and ended when system shuts down Run in the background with no controlling terminal.
1 Loops. 2 Often we want to execute a block of code multiple times. Something is always different each time through the block. Typically a variable is.
15-213/ Intro to Computer Systems by btan with reference to Spring 10’s slides.
Scripting Languages Chapter 6 I/O Basics. Input from STDIN We’ve been doing so with $line = chomp($line); Same as chomp($line= ); line input op gives.
Terminal Control Many special files represent devices that are platform dependent, making standardization difficult POSIX standards committee decided to.
Chapter 7 Programming with DOS and BIOS Function Calls Objectives: The use of DOS and BIOS function call How to read the PC’s keyboard How to send text.
Dynamic visualizations On ‘non-canonical’ keyboard-input and terminal escape-sequences for visualization effects.
Non-blocking I/O int flags; int fd; /* file descripter */ void main() { fd = open(“myfile.txt”, R_ONLY); if ((flags = fcntl(fd, F_GETFL, 0)) < 0) /* first.
CSE 451 Section 4 Project 2 Design Considerations.
Guide To UNIX Using Linux Third Edition
C Programming. C vs C++ C syntax and C++ syntax are the same but... C is not object oriented * There is no string class * There are no stream objects.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
Advanced Shell Programming. 2 Objectives Use techniques to ensure a script is employing the correct shell Set the default shell Configure Bash login and.
CMPE13 Cyrus Bazeghi Chapter 18 I/O in C. CMPE Standard C Library I/O commands are not included as part of the C language. Instead, they are part.
Chapter 5. Connection Controls. Device == File ? Filenames Properties permission bits system call – open, read, write, lseek, close, stat.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
Signal-Driven I/O Concepts and steps for using signal-driven I/O
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
Computer programming Lecture 4. Lecture 4: Outline Making Decisions [chap 6 – Kochan] –The if Statement –The if-else Construct –Logical Operators –Boolean.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
Shell (Part 2). Example r What if we want to support something like this: m ps –le | sort r One process should execute ps –le and another should execute.
Chapter 18 I/O in C.
More on UART Interrupts; System Calls Reference on Interrupt Identification Register(IIR) slide 17 of
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 8: Opening Files and Starting Processes.
The tty Interface An introduction to “systems programming” in the Linux environment.
ITEC 502 컴퓨터 시스템 및 실습 Chapter 2-1: Process Mi-Jung Choi DPNM Lab. Dept. of CSE, POSTECH.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
File IO and command line input CSE 2451 Rong Shi.
Shell (Addendum). Example r What if we want to support something like this: m ps –le | sort r One process should execute ps –le and another should execute.
8086 Microprocessor Interrupts By: Vijay Kumar. K Reference From Slide Share.
1 © 2012 John Urrutia. All rights reserved. Chapter 6 The vi Editor.
Operating Systems Process Creation
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
Input/output streams. Character Input / Output and Input Validation Input and output devices: keyboards, disk drives, mouse, monitors, printers, network.
Implementing ‘noecho’ Programming details regarding the Linux implementation for ‘struct termios’ objects.
Today’s topics Signals and how to control the program behavior in handling signals. Terminal I/O.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Control Structure vs. Assembly Language NASM. If-then-else If conditional then then_actions jump to endif else else_actions endif.
Integers/Characters Input/Output Integers and Characters Input/Output System Calls. syscall Trap Handler Services for Integers and Characters Read Integer,
CSCI 330 UNIX and Network Programming Unit XVII: Socket Programming Detail.
The Process CIS 370, Fall 2009 CIS UMassD. The notion of a process In UNIX a process is an instance of a program in execution A job or a task Each process.
Files A collection of related data treated as a unit. Two types Text
1 Lecture 19: Unix signals and Terminal management n what is a signal n signal handling u kernel u user n signal generation n signal example usage n terminal.
CHARACTER INPUT / OUTPUT AND INPUT VALIDATION. Introduction Input and output devices: keyboards, disk drives, mouse, monitors, printers. I/O functions.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
Process Related System Calls By Neha Hulkoti & Kavya Bhat.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
CCSA 221 Programming in C INPUT AND OUTPUT OPERATIONS IN C – PART 1 1.
Real Numbers Device driver process within the operating system that interacts with I/O controller logical record 1 logical record 2 logical record 3.
File I/O. I/O Flags Flags are passed to give some information about how the file is to be used. – Read only file – flag=0x0 – Write only file – flag=0x1.
Exercise ● Exercise 4.15: Write a version of mkdir which supports the - p option. Due by class 2/23....
Chapter 18 I/O in C.
Session #5 File I/O Bit Masks, Fields & Bit Manipulations
Files I/O, Streams, I/O Redirection, Reading with fscanf
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Advanced UNIX programming
FILE HANDLING IN C.
File Input and Output.
Chapter 18 I/O in C.
Presentation transcript:

Terminal Control operating systems

Terminal Control may seem like an arcane subject, but … It illustrates the relationship between devices and files The terminal driver is an easy device driver to work with operating systems

Consider the following code: #include int main ( ) { int c, n = 0; while( ( c = getchar( ) ) != ‘Q’ ) printf ( “char %3d is %c code %d\n”, n++, c, c); return 0; } Run it..... (listchars.c)

The program does not process any data until the Enter key is hit. The enter key generates a Carriage Return character, 13 but the program receives the character code 10, New Line. Some Observations

Moreover, when the program outputs a New Line character, it outputs as a Carriage Return. New Line only move the cursor down one line, it does not move the cursor to the left margin! Some Observations

The Terminal Driver Terminal Driver Application operating systems The Terminal driver is doing some manipulation of the data as it flows between the terminal and your program!

The Terminal Driver Terminal Driver Application operating systems These manipulations are controlled by terminal attributes that can be changed by a process. attributes

Terminal Attributes To see the current set of terminal attributes stty stty -a

$ stty -a speed 9600 baud; 24 rows; 80 columns;... iflags: -istrp icrnl -inlcr... input flags: what the driver does with characters coming from the terminal - the flag is turned off convert cr to nl man stty to see more detail

You can alter setting with the stty command stty -echo This turns off echo mode

Terminal Modes Canonical or cooked mode The terminal driver stores incoming characters in a buffer Sends characters to the application a line at a time Handles basic editing functions (delete, backspace, …) operating systems

The Terminal Driver Terminal Driver Application operating systems characters lines canonical mode buffer Process Backspace, etc

Terminal Modes Non-Canonical or cr-break mode The terminal driver does not buffer keyboard input Sends characters to the application a character at a time, as it is entered Does some character processing * Ctrl-C (interrupt) * carriage return to newline operating systems

The Terminal Driver Terminal Driver Application operating systems non-canonical mode characters Process Ctrl-C, CR-NL

Terminal Modes Raw mode The terminal driver does not buffer keyboard input. Sends characters to the application a character at a time Does no character processing operating systems

The Terminal Driver Terminal Driver Application operating systems raw mode

The Terminal Driver Terminal Driver Application operating systems You control the Terminal driver by manipulating A set of terminal attributes stored in the device driver. tcgetattr( ) tcsetattr( ) driver attributes

Reading Attributes from the Terminal Driver #include int result = tcgetattr(int fd, struct termios* attrs); returns 0 if successful -1 if an error zero for stdin address of a termios struct operating systems

Setting Attributes in the Terminal Driver #include int result = tcsetattr(int fd, int when, struct termios* attrs); returns 0 if successful -1 if an error zero for stdin address of a termios struct when to apply the settings TCSANOW – immediately TCSADRAIN – after draining queued data TCSAFLUSH – after draining + flush input operating systems Note: Some shells will reset these attributes in an effort to protect you from yourself.

The termios struct struct termios { tcflag_t c_iflag;/* input mode flags */ tcflag_t c_oflag;/* output mode flags */ tcflag_t c_cflag;/* control mode flags */ tcflag_t c_lflag;/* local mode flags */ cc_t c_cc[NCCS]; /* control characters */ speed_t c_ispeed;/* input speed */ speed_t c_ospeed;/* output speed */ }; operating systems

flagsflags c_lflag ISIG – enable signals ICANON – canonical mode ECHO – enable echo operating systems All of these flags have symbolic constants. To see all of the fields in the termios structure see termios man pages.

MaskingMasking operating systems

Bitwise Operators &and |or ~complement a b a & b a b a | b operating systems Remember your boolean logic?

To Set a flag flag = flag | mask 0’s except for the bits to be set in the flag flag mask flag | mask operating systems this bit got set

To Clear a flag flag = flag & ~mask 1’s except for the bits to be cleared in the flag flag mask ~ mask flag & ~mask operating systems this bit got cleared

To Test a flag if ( flag == flag & mask ) flag mask flag & mask operating systems Remember that in C, 0 is false and non-zero is true. set the bits in the mask that you want to test in the flag if ( flag & mask )

ExampleExample operating systems #include int main ( ) { struct termios info; int rv; if ( (rv = tcgetattr( 0, &info ) ) == -1 ) { perror(“tcgetattr error”); exit ( 1 ); } if ( info.c_lflag & ECHO) printf(“ echo flag is set\n”); else printf(“ echo flag is not set\n”); return 0; } file descriptor is 0 for stdin Examine Echo flag test the flag Run... echostate.c

ExampleExample operating systems if ( (rv = tcgetattr( 0, &info ) ) == -1 ) { perror(“tcgetattr error”); exit ( 1 ); } if ( argv[1][0] == ‘y’ ) info.c_lflag |= ECHO; else info.c_lflag &= ~ECHO; if ( tcsetattr ( 0, TCSANOW, &info ) == -1) { perror(“tcsetattr error”); exit ( 1 ); } Change Echo flag set the flag clear the flag Run... setecho.c

Writing a Terminal Program operating systems do some work ask if user wants to do more get response no yes Molay chapter 6

operating systems Because the terminal is in canonical mode, The user has the following problems: 1. The user has to press the enter key before the program can act on the input. 2. The user can type something other than ‘y’ or ‘n’ and nothing happens.

operating systems do some work ask if user wants to do more no yes turn off canonical mode turn on canonical mode get response response ?

operating systems This works great, but replying to every illegal keystroke is annoying! The solution: Turn off echo mode and ignore illegal keystrokes.

operating systems What if this program was running in an atm machine, and the person walked away without typing ‘y’ or ‘n’? Someone else could walk up and run a transaction using this person’s account.

operating systems Blocking vs Non-blocking I/O read do something The normal read operation waits until the read operation is satisfied before going on to the next instruction.

operating systems Blocking vs Non-blocking I/O read do something It is possible to use fcntl or open to change the properties of a file so that when the file is read, the program does not wait for the read to finish, but goes on immediately to the next instruction. The read instruction returns a 0 if no data has been read.

Using fcntl( ) #include int fcntl(int filedes, int cmd, … /* int arg */); F_DUPFD - duplicate the file descriptor F_GETFD - get the file descriptor flags F_SETFD - set the file descriptor flags F_GETFL - get the file status flags F_SETFL - set the file status flags...

File status flags O_RDONLYopen file for reading only O_WRONLYopen file for writing only O_RDWRopen for reading and writing O_APPENDappend on each write O_NONBLOCKnon-blocking mode O_SYNCwait for writes to complete O_ASYNCasynchronous I/O (bsd and 4.3)

void set_nodelay_mode( ) { int termflags; termflags = fcntl(0, F_GETFL); termflags |= NONBLOCK; fcntl(0, F_SETFL, termflags); } get the file descriptor flags set non-blocking flag save the new flags

operating systems int get response(char* question, int maxtries) { int input; printf(“%s (y/n)?”, question); flush (stdout); while (1) { sleep(SLEEPTIME); input = tolower(get_ok_char( ) ); if ( input == ‘y’ ) return 1; if ( input == ‘n’ ) return 0; if ( maxtries -- == 0) return 2; } print the question

operating systems int get response(char* question, int maxtries) { int input; printf(“%s (y/n)?”, question); flush (stdout); while (1) { sleep(SLEEPTIME); input = tolower(get_ok_char( ) ); if ( input == ‘y’ ) return 1; if ( input == ‘n’ ) return 0; if ( maxtries -- == 0) return 2; } The o/s won’t flush the buffer until it sees a newline or until the program tries to read. and the read doesn’t happen until here. timeout

operating systems char get_ok_char( ) { int c: while ( ( c = getchar( ) ) != EOF && strchr(“YyNn”, c) == NULL); return c; } Drops out if EOF is returned. Note that when read is non- blocking an EOF is returned when there is no data. In this case, the EOF ( 0 ) gets returned.

operating systems char get_ok_char( ) { int c: while ( ( c = getchar( ) ) != EOF && strchr(“YyNn”, c) == NULL); return c; } Or it drops out when one of ‘Y’, ‘y’, ‘N’, or ‘n’ is typed. In this case, the typed character is returned. The strchr( str1, c) function looks for the character c in the string str1. It returns a pointer to the character or NULL if the character is not found.

Your more command should work as follows: Your program will display the first 23 lines of the file. On the last line of the screen, it will then display the file name of the file being displayed, and the percentage of the file which has been displayed. It then will wait for user input. The user has three choices at this point: If the user types a 'q', then your program exits. If the user types a space, then your program displays the next 23 lines of the file. If the user presses the ENTER key, then just the next line of the file is displayed. Note that invalid keystrokes are ignored and keystrokes are not echoed back to the screen. In the last two cases, your program should just display the percentage of the file that has been displayed. It only displays the file name on the first screen displayed. Don’t allow the file name and percentage to scroll up the screen as new lines of data from the file are displayed.