Download presentation
Presentation is loading. Please wait.
Published byJared Stafford Modified over 9 years ago
1
Chapter 5. Connection Controls
2
Device == File ? Filenames Properties permission bits system call – open, read, write, lseek, close, stat
3
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)
4
Device == File ? Device Files and Inodes
5
Device != File ? Disk Files vs Terminal Files – Devices have their own attributes. Connection attributes - we can control attributes in a different way.
6
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
7
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”);
8
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”);
9
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.
10
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 $
11
Change settings -Terminal The stty command $stty erase X#make ‘X’ the erase key $stty –echo #type invisibly $stty erase @ echo #multiple requests
12
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
13
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
14
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
15
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*/ };
17
Example – Echo State
18
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); }
19
Example – display attribs
22
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
23
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; }
24
Chapter 6. Programming for Humans
25
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
26
Device-Specific Program Programs that interact with specific devices Ex) scanner, camera, cd-rom, … In this chapter, we make terminal-specific program. user-program !
27
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
28
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.
29
Canonical mode
30
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
31
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
32
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
33
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; }
34
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; }
35
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
36
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 */
37
/* 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; }
38
/* 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; }
39
/* 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); }
40
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 */ }
41
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!
42
Ctrl-C kills process
43
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
44
Signals What does Ctrl-C do? - Ctrl-C interrupts program It generates a signal ! Signal is a kernel mechanism Simple and powerful
45
What does Ctrl-C do ?
46
What is signal ? Signal : One-word message Ex) go, stop, out, green light Each signal has a numerical code. – Interrupt signal is No. 2.
47
Where do signals come from? User, Kernel, other process
48
List of signals /usr/include/signal.h
49
When a signal comes … Process have 3 choices: 1. Accept - signal(SIGINT, SIG_DFL) 2. Ignore - signal(SIGINT, SIG_IGN) 3. Call a function
50
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
51
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"); }
52
How sigdemo1 works
53
Run sigdemo1 $./sigdemo1 hello hello (press Ctrl-C !) OUCH! hello
54
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"); }
55
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?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.