Chapter 5. Connection Controls. Device == File ? Filenames Properties permission bits system call – open, read, write, lseek, close, stat.

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.
Terminal I/O POSIX termios Two terminal I/O modes Canonical and non-canonical Getting and setting terminal attributes Terminal window size: struct winsize.
I/O Multiplexing Road Map: 1. Motivation 2. Description of I/O multiplexing 3. Scenarios to use I/O multiplexing 4. I/O Models  Blocking I/O  Non-blocking.
NCHU System & Network Lab Lab 15 Record Locking. NCHU System & Network Lab Record Locking (1/4) What happens when two process attempt to edit the same.
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.
Lesson 10-Controlling User Processes. Overview Managing and processing processes. Managing jobs. Exiting/quitting when jobs have been stopped.
1 © 2001 John Urrutia. All rights reserved. Chapter 5 The Shell Overview.
UNIX Process Control Bach 7 Operating Systems Course Hebrew University Spring 2007.
Terminal Control operating systems. Terminal Control may seem like an arcane subject, but … It illustrates the relationship between devices and files.
1 Processes Professor Jennifer Rexford
CS 311 – Lecture 09 Outline Introduction to Systems programming – System calls – Categories of system calls Error Management System calls File Handling.
Terminal Control Many special files represent devices that are platform dependent, making standardization difficult POSIX standards committee decided to.
Signals Hua LiSystems ProgrammingCS2690Signals. Topics: Sending Signals -- kill(), raise() Signal Handling -- signal() sig_talk.c -- complete example.
Dynamic visualizations On ‘non-canonical’ keyboard-input and terminal escape-sequences for visualization effects.
Operating Systems Course Hebrew University Spring 2007 Signals & User Thread.
More Shell Basics CS465 - Unix. Unix shells User’s default shell - specified in /etc/passwd file To show which shell you are currently using: $ echo $SHELL.
Introduction to Linux and Shell Scripting Jacob Chan.
UNIX Signals Bach 7.2 Operating Systems Course The Hebrew University Spring 2010.
Tanenbaum & Woodhull, Operating Systems: Design and Implementation, (c) 2006 Prentice-Hall, Inc. All rights reserved OPERATING SYSTEMS DESIGN.
Adv. UNIX: lowIO/161 Advanced UNIX v Objectives –look at low-level operations for handling files Special Topics in Comp. Eng. 2 Semester.
Introduction to UNIX / Linux - 11
1 Shell Programming – Extra Slides. 2 Counting the number of lines in a file #!/bin/sh #countLines1 filename=$1#Should check if arguments are given count=0.
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
C Basic File Input/Output Manipulation C Programming – File Outline v File handling in C - opening and closing. v Reading from and writing to files.
1Reference “Introduction To Unix Signals Programming” in the reference material section Man page – sigprocmask, alarm “Understanding the Linux Kernel”
Recitation 9: Error Handling, I/O, Man Andrew Faulring Section A 4 November 2002.
Additional UNIX Commands. 222 Lecture Overview  Multiple commands and job control  More useful UNIX utilities.
Chapter 2: Linux & POSIX “She sells bash shells by the C shore”
File Handling Spring 2013Programming and Data Structure1.
Agenda Link of the week Use of Virtual Machine Review week one lab assignment This week’s expected outcomes Review next lab assignments Break Out Problems.
Nonblocking I/O Blocking vs. non-blocking I/O Nonblocking input, output, accept, and connect Readings –UNP Ch16 1.
1 Operating Systems Lecture 2 UNIX and Shell Scripts.
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.
Agenda  Working with Processes: Purpose Running Programs within same process (execl, execlp, execle, execv, execvp, execve) “Spawning” other process (fork,
Lecture 24CS311 – Operating Systems 1 1 CS311 – Lecture 24 Outline Final Exam Study Guide Note: These lecture notes are not intended replace your notes.
Chapter Four I/O Redirection1 System Programming Shell Operators.
1 Signals (continued) CS 241 April 9, 2012 University of Illinois.
Operating Systems Recitation 4, April th, 2002 Signals.
Input/output streams. Character Input / Output and Input Validation Input and output devices: keyboards, disk drives, mouse, monitors, printers, network.
Lesson 3-Touring Utilities and System Features. Overview Employing fundamental utilities. Linux terminal sessions. Managing input and output. Using special.
Implementing ‘noecho’ Programming details regarding the Linux implementation for ‘struct termios’ objects.
C Homework Write mypaste.c and mycomm.c – mypaste is like paste & mycomm is like comm – Both take two files as arguments – Paste reads a line from each.
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()”
Recitation 9: Error Handling, I/O, Man Anubhav Gupta Section D.
File I/O open close lseek read and write – unbuffered I/O dup and dup2.
S -1 Processes. S -2 wait and waitpid (11.2) Recall from a previous slide: pid_t wait( int *status ) wait() can: (a) block; (b) return with status; (c)
CSCI 330 UNIX and Network Programming Unit XVII: Socket Programming Detail.
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.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
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.
The Shell What does a shell do? - execute commands, programs - but how? For built in commands run some code to do the command For other commands find program.
Exercise ● Exercise 4.15: Write a version of mkdir which supports the - p option. Due by class 2/23....
G.Jyostna.
Introduction to Operating Systems
CSE 303 Concepts and Tools for Software Development
Files I/O, Streams, I/O Redirection, Reading with fscanf
CSE 390a Lecture 2 Exploring Shell Commands, Streams, and Redirection
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Advanced UNIX programming
Programming and Data Structure
Exploring Shell Commands, Streams, and Redirection
CSE 390a Lecture 2 Exploring Shell Commands, Streams, and Redirection
Standard I/O Library Implementation
File I/O & UNIX System Interface
Exploring Shell Commands, Streams, and Redirection
Presentation transcript:

Chapter 5. Connection Controls

Device == File ? Filenames Properties permission bits system call – open, read, write, lseek, close, stat

Device == File ? Example: tty mode link owner Last_modified filename inode * Directory(d), Symbolic Link(l), Character Device(c), Block Device(b) group major # : Device Driver minor # : Device modeownergroupsizeLast_modifiedfilename link (chapter 2)

Device == File ? Device Files and Inodes

Device != File ? Disk Files vs Terminal Files – Devices have their own attributes. Connection attributes - we can control attributes in a different way.

System call: fcntl fcntl PURPOSEControl file descriptors INCLUDE#include USAGEint result = fcntl(int fd, int cmd); int result = fcntl(int fd, int cmd, long arg); int result = fcntl(int fd, int cmd, struct flock *lockp); ARGSfd cmd arg lock the file descriptor to control the operation to perform arguments to the operation lock information RETURNS-1 Other if error depends on operation

Change settings -Disk 3-steps for controlling filedesciptors #include int s; s = fcntl(fd, F_GETFL); //step1. get flags s |= O_SYNC; //step2. modify flags result = fcntl(fd,F_SETFL,s); //step3. set flags if(result == -1) perror(“setting SYNC”);

Change settings -Disk If two people log in at the same time, how can this Race Condition be avoided? Auto Append #include int s; s = fcntl(fd, F_GETFL); s |= O_APPEND; result = fcntl(fd,F_SETFL,s); if(result == -1) perror(“setting APPEND”);

Controlling File Descriptors fd = open(file_name, flags) – fd = open(fn, O_WRONLY|O_APPEND|O_SYNC); Flags – O_CREAT: Create the file if it does not exist. – O_TRUNC: If the file exists, truncate the file to length zero. – O_EXCL: This flag is intended to prevent wo processes from creating the same file. The second call returns -1.

Attribute of Terminal A simple example #include main() { int c, n = 0; while((c = getchar()) != 'Q') printf("char %3d is %c code %d\n", n++, c, c); } $./a.out hello char 0 is h code 104 char 1 is e code 101 char 2 is l code 108 char 3 is l code 108 char 4 is o code 111 char 5 is code 10 Q $

Change settings -Terminal The stty command $stty erase X#make ‘X’ the erase key $stty –echo #type invisibly $stty echo #multiple requests

Change settings -Terminal 3-steps for changing terminl driver #include struct termios attribs; tcgetattr(fd, &attribs); //step1. get attribs settings.c_lflag |= O_ECHO; //step2. modify attribs tcsetattr(fd, TCSANOW, &attribs); //step3. send attribs ☞ TCSANOW, TCSADRAIN, TCSAFLUSH

function: tcgetattr tcgetattr PURPOSERead attributes from tty driver INCLUDE #include USAGEint result = tcgetattr(int fd, struct termios *info); ARGS fd info the file descriptor connected to a terminal pointer to a struct termios RETURNS -1 0 if error If success

function: tcsetattr tcsetattr PURPOSESet attributes in tty driver INCLUDE #include USAGEint result = tcsetattr(int fd, int when, struct termios *info); ARGS fd when info the file descriptor connected to a terminal when to change the settings pointer to a struct termios RETURNS -1 0 if error If success

struct termios { tcflag_t c_iflag; /*input mode flags*/ tcflag_t c_oflag; /*output mode flags*/ tcflag_t c_cflag; /*control mode flags*/ tcflag_tc_lflag; /*local mode flags*/ cc_t c_cc[NCCS];/*control charters*/ speed_t c_ispeed;/*input speed*/ speed_t c_ospeed;/*output speed*/ };

Example – Echo State

Example – change state #include #define oops(s,x) { perror(s);exit(x);} main(int ac, char *av[]) { struct termios info; if(ac==1) exit(0); if(tcgetattr(0, &info) == -1) //get attribs oops(“tcgetattr”, 1); if(av[1][0] == ‘y’) info.c_lflag |= ECHO; //turn on bit else info.c_lflag &= ~ECHO; //turn off bit if(tcsetattr(0,TCSANOW, &info) == -1) //set attribs oops(“tcsetattr”, 2); }

Example – display attribs

Other Devices? System call: ioctl ioctl PURPOSEControl a device INCLUDE#include USAGEint result = ioctl(int fd, int operation (, arg…) ); ARGS fd operation info the file descriptor connected to device Operation to perform Any args required for the operation RETURNS other if error Depends on device

Example #include int main() { struct winsize wbuf; if(ioctl(0, TIOCGWINSZ, &wbuf) != -1) printf("%d rows x %d cols\n", wbuf.ws_row, wbuf.ws_col); return 0; }

Chapter 6. Programming for Humans

Software tools Programs that see no difference between disk files and devices Ex) who, ls, sort, uniq, grep, tr, du, … Read stdin or files, Write to stdout and stderr. – $ sort > outputfile – $ sort x > /dev/lp

Device-Specific Program Programs that interact with specific devices Ex) scanner, camera, cd-rom, … In this chapter, we make terminal-specific program.  user-program !

User-Program Consider how the keystrokes are handled and output is processed. Common concerns of user program (a) immediate response to keys (b) limited input set (c) timeout on input (d) resistance to Ctrl-C

Modes of the terminal driver Raw mode - Sends entire sequence of characters. Canonical mode - Erase characters before sending the revised sequence to the reading process. - Processes edit and delete.

Canonical mode

Modes of the terminal driver Example input Hello data DEL DEL DEL DEL world RAW mode output Hello data DEL DEL DEL DEL world Canonical mode output Hello world

Example #include intmain( ) { intc; while((c = getchar( )) != EOF) { if(c == ‘z’) c = ‘a’; else if(islower(c)) c++; putchar(c); } $./a.out abx  cd ???? efg $ stty -icannon $./a.out ???? $ stty icannon * In Canonical Mode* In Non-Canonical Mode

Writing a User Program #!/bin/sh while true do do_a_transaction if play_again# our target then continue fi break done Accept input if “y” : return 0 if “n” : return 1 y : loop back n : break What play_again does is Prompt User with Question If “y”, return 0 If “n”, return 1

First play_again #include #defineQUESTION"Do you want another transaction“ intget_response(char *q) { printf("%s (y/n)?", q); while(1) { switch(getchar()) { case 'y': case 'Y': return 0; case 'n': case 'N': case EOF: return 1; } intmain() { intresponse; response = get_response(QUESTION); return response; }

Second play_again: immediate response int set_crmode() { struct termios ttystate; tcgetattr(0, &ttystate); ttystate.c_lflag &= ~ICANON; ttystate.c_cc[VMIN] = 1; tcsetattr(0, TCSANOW, &ttystate); } int tty_mode(int how) { static struct termios original_mode; if(how == 0) { tcgetattr(0, &original_mode); return 0; } return tcsetattr(0, TCSANOW, &original_mode); } int main() { int response; tty_mode(0); set_crmode(); response = get_response(QUESTION); tty_mode(1); return response; }

Non-blocking mode Blocking – getchar() or read()  wait for input How to set non-blocking – Use O_NDELAY in open or fcntl New play_again – Timeout feature. – Telling the terminal drive not to wait – No input found then sleep for few seconds and look again for input – After three tries give up

New play_again /* play_again.c purpose: Ask if you want another transaction Method : set tty into chr-by-chr, no-echo mode set tty into no-delay mode read char, return result Returns: 0=> yes, 1=> no, 2=> timeout Better : rest the terminal mode on interrupt */ #include #define ASK "Do you want another transaction“ #define TRIES 3 /* maximum tries*/ #define SLEEPTIME 2 /* time per try */ #define BEEP putchar('\a')/* alert user */

/* play_again.c continued */ main( ) { int response; tty_mode(0); /* save current mode*/ set_cr_noecho_mode(); /* set –icanon, echo */ set_nodelay_mode(); /* noinput => EOF */ /* get some answer */ response = get_response(ASK, TRIES); tty_mode(1);/* restore orig mode */ return response; }

/* purpose : ask a question and wait for y/n answer or maxtries * method : use getchsr and complain about non –y/n input * returns : 0=> yes, 1=> no, 2=> timeout */ get_response(char* question, int maxtries) { int input; printf ("%s (y/n)?", question); /* ask*/ fflush(stdout); /* force output */ while(1) { sleep(SLEEPTIME); /* wait a bit*/ input = tolower(get_ok_char()); /* get next char*/ if (input == 'y') return 0; if (input == 'n') return 1; if (maxtries-- == 0) /* out time? */ return 2; /* say no */ BEEP; }

/* skip over ilegal chars and return y,Y,n,N or EOP */ get_ok_char( ) { int c; while ((c = getchar())!=EOF && strchr("yYnN",c) == NULL) ; return c; } /* how == 0 => save current mode, how ==> 1 restore mode */ /* this version handles termios and fcnt1 flags */ tty_mode(int how) { static struct termios original_mode; static int original_flags; if (how == 0) { tcgetattr(0, &original_mode); orginal_flags= fcntl(0, F_GETFL); } else { return tcsetattr(0, TCSANOW, &original_mode); fcnt1 (0, F_SETFL, orginal_flags); }

set_nodelay_mode( ) { int termflags; termflags = fcntl(0, F_GETFL); /* read current setting */ termflags |= O_NDELAY; /* flip on nodelay bit */ fcntl(0, F_SETFL, termflags); /* and install em */ } set_cr_noecho_mode( ) { struct termios ttystate; tcgetattr(0, &ttystate); /* read current settings */ ttystate.c_lflag &= ~ICANON; /* no buffering */ ttystate.c_lflag &= ~ECHO; /* no echo either */ ttystate.c_cc[VMIN] = 1; /* get 1 char at a time */ tcsetattr(0, TCSANOW, &ttystate); /* install settings */ }

Others methods to implement timeouts What happens when Ctrl–C is pressed? $ make play_again3 cc play_again3.c -o play_again3 $./ play_again3 Do you want another transaction (y/n)? Press Ctrl-C now $ logout Connection to host closed bash$ What is the problem of the sequence above? Couldn’t restore ttys!

Ctrl-C kills process

User-Program Consider how the keystrokes are handle and output is processed. Common concerns of user program (a) immediate response to keys (b) limited input set (c) timeout on input (d) resistance to Ctrl-C

Signals What does Ctrl-C do? - Ctrl-C interrupts program  It generates a signal ! Signal is a kernel mechanism Simple and powerful

What does Ctrl-C do ?

What is signal ? Signal : One-word message Ex) go, stop, out, green light Each signal has a numerical code. – Interrupt signal is No. 2.

Where do signals come from? User, Kernel, other process

List of signals /usr/include/signal.h

When a signal comes … Process have 3 choices: 1. Accept - signal(SIGINT, SIG_DFL) 2. Ignore - signal(SIGINT, SIG_IGN) 3. Call a function

How to call a function signal(signum, functionname); signal PURPOSESimple signal handling INCLUDE#include USAGEresult = signal(int signum, void(*action)(int)) ARGS signum : the signal to respond to action : how to respond RETURNS -1 if error prevaction if success

Examples of signal handling sigdemo1.c : catching a signal #include main(){ void f(int); int i; signal(SIGINT, f); for (i=0;i<5;i++){ printf("hello\n"); sleep(1); } void f(int signum){ printf("OUCH!\n"); }

How sigdemo1 works

Run sigdemo1 $./sigdemo1 hello hello (press Ctrl-C !) OUCH! hello

Examples of signal handling sigdemo2.c : ignoring a signal #include main(){ signal(SIGINT, SIG_IGN); printf("you can't stop me!\n"); while(1){ sleep(1); printf("haha\n"); }

Run sigdemo2 $./sigdemo2 you can’t stop me! haha haha (press Ctrl-C !) (SIGINT) haha haha (press Ctrl-\ !) (SIGQUIT) $ What count is the number of printed “haha”s! Why only four times?