COMP 530: Operating Systems Basic OS Programming Recap .

2y ago
9 Views
3 Downloads
959.12 KB
8 Pages
Last View : 11d ago
Last Download : 2m ago
Upload by : Jewel Payne
Transcription

10/1/16COMP 530: Operating SystemsCOMP 530: Operating SystemsRecapBasic OS ProgrammingAbstractions(and Lab 1 Overview) We’ve introduced the idea of a process as acontainer for a running program This lecture: Introduce key OS APIs for a process– Some may be familiar from lab 0– Some will help with lab 1Don PorterPortions courtesy Kevin Jeffay1COMP 530: Operating SystemsCOMP 530: Operating SystemsLab 1: A (Not So) Simple ShellTasks Last year: Most of the lab focused on just processinginput and output Turn input into commands; execute those commands– Kind of covered in lab 0– Support PATH variablesBe able to change directoriesPrint the working directory at the command lineAdd debugging supportAdd variables and scripting supportPipe indirection: , , and Job control (background & foreground execution)goheels – draw an ASCII art Tar Heel – I’m giving you some boilerplate code that does basics– Reminder: demo My goal: Get some experience using process APIs– Most of what you will need discussed in this lecture You will incrementally improve the shell3Significantly more work than Lab 0 – start early!4COMP 530: Operating SystemsOutline Fork recapFiles and File HandlesInheritancePipesSocketsSignalsSynthesis Example: The ShellCOMP 530: Operating SystemsProcess Creation: fork/join in Linux The execution context for the child process is a copy ofthe parent’s context at the time of the callmain {int childPID;S1 ;fork()childPID fork();if(childPID 0) code for child process else { code for parent process wait();}S2 ;}CodechildPID 0DataStackParentCodeDatachildPID xxxStackChild1

10/1/16COMP 530: Operating SystemsProcess Creation: exec in Linux exec allows a process to replace itself with another program– (The contents of another binary file)foo:main {S’}COMP 530: Operating SystemsProcess Creation: Abstract fork in Linux The original fork semantics can be realized in Linux via a(UNIX) fork followed by an execmain {int childPID;S1 ;exec()fork()exec()childPID fork();a.out:main {S0exec(foo)S1S2}if(childPID 0)exec(filename)else { code for parent process entChild. /fooMemoryContextS2 ;}COMP 530: Operating SystemsCOMP 530: Operating Systems2 Ways to Refer to a FilePath-based calls Path, or hierarchical name, of the file Functions that operate on the directory tree– Absolute: “/home/porter/foo.txt”– Rename, unlink (delete), chmod (change permissions), etc. Starts at system root Open – creates a handle to a file– Relative: “foo.txt”– int open (char *path, int flags, mode t mode); Assumes file is in the program’s current working directory Flags include O RDONLY, O RDWR, O WRONLY Permissions are generally checked only at open Handle to an open file– Handle includes a cursor (offset into the file)– Opendir – variant for a directoryCOMP 530: Operating SystemsCOMP 530: Operating SystemsHandle-based calls ssize t read (int fd, void *buf, size t count)– Fd is the handle– Buf is a user-provided buffer to receive count bytes of thefile– Returns how many bytes read ssize t write(int fd, void *buf, size t count)– Same idea, other direction int close (int fd)– Close an open filemain {S’}ExamplePCchar buf[9];int fd open (“foo.txt”, O RDWR);Awesome\0ssize t bytes read(fd, buf, 8);if (bytes ! 8) // handle the errorfd: 3bufbytes: 8memcpy(buf, “Awesome”, 7);buf[7] ‘\0’;bytes write(fd, buf, 8);if (bytes ! 8) // errorclose(fd);User-level stackHandle 3KernelContents\0AwesomeContentsfoo.txt2

10/1/16COMP 530: Operating SystemsHandlescanbeLogicalsharedBut what is a handle? A reference to an open file or other OS object– For files, this includes a cursor into the file In the application, a handle is just an integerHello!– This is an offset into an OS-managed tableViewVirtual Address Space50Foo.txtinodeHandle indicesare processspecificDiskCOMP 530: Operating SystemsProcess A20Process BHandleTableCOMP 530: Operating Systems– E.g., a file handle includes the offset into the file and apointer to the kernel-internal file representation (inode)Process CCOMP 530: Operating SystemsHandle Recap Every process has a table of pointers to kernel handleobjectsHandle TableRearranging the table The OS picks which index to use for a new handle An application explicitly copy an entry to a specificindex with dup2(old, new)– Be careful if new is already in use Application’s can’t directly read these pointers– Kernel memory is protected– Instead, make system calls with the indices into this table– Index is commonly called a handleCOMP 530: Operating SystemsCOMP 530: Operating SystemsOther useful handle APIs mmap() – can map part or all of a file into memory seek() – adjust the cursor position of a file– Like rewinding a cassette tapeOutline Files and File HandlesInheritancePipesSocketsSignalsSynthesis Example: The Shell3

10/1/16COMP 530: Operating SystemsCOMP 530: Operating SystemsInheritance By default, a child process gets a reference to everyhandle the parent has openStandard in, out, error Handles 0, 1, and 2 are special by convention– 0: standard input– 1: standard output– 2: standard error (output)– Very convenient– Also a security issue: may accidentally pass something theprogram shouldn’t Between fork() and exec(), the parent has a chanceto clean up handles it doesn’t want to pass on Command-line programs use this convention– Parent program (shell) is responsible to useopen/close/dup2 to set these handles appropriatelybetween fork() and exec()– See also CLOSE ON EXEC flagCOMP 530: Operating SystemsCOMP 530: Operating SystemsExampleint pid fork();if (pid 0) {int input open (“in.txt”,O RDONLY);dup2(input, 0);exec(“grep”, “quack”);}// Outline Files and File HandlesInheritancePipesSocketsSignalsSynthesis Example: The ShellCOMP 530: Operating SystemsPipes FIFO stream of bytes between two processes Read and write like a file handle––––But not anywhere in the hierarchical file systemAnd not persistentAnd no cursor or seek()-ingActually, 2 handles: a read handle and a write handle Primarily used for parent/child communication– Parent creates a pipe, child inherits itCOMP 530: Operating SystemsExamplePC int pipe fd[2];int rv pipe(pipe fd);PC int pid fork();if (pid 0) {close(pipe fd[1]);dup2(pipe fd[0], 0);close(pipe fd[0]);exec(“grep”, “quack”);} else {close (pipe fd[0]);.WVirtual Address SpaceHandle TableParentRChild4

10/1/16COMP 530: Operating SystemsCOMP 530: Operating SystemsSocketsSelect Similar to pipes, except for network connections Setup and connection management is a bit trickier– A topic for another day (or class) What if I want to block until one of several handleshas data ready to read? Read will block on one handle, but perhaps miss dataon a second Select will block a process until a handle has dataavailable– Useful for applications that use pipes, sockets, etc.COMP 530: Operating SystemsCOMP 530: Operating SystemsOutline SignalsFiles and File HandlesInheritancePipesSocketsSignalsSynthesis Example: The Shell Similar concept to an application-level interrupt– Unix-specific (more on Windows later) Each signal has a number assigned by convention– Just like interrupts Application specifies a handler for each signal– OS provides default If a signal is received, control jumps to the handler– If process survives, control returns back to applicationCOMP 530: Operating SystemsSignals, cont. Can occur for:– Exceptions: divide by zero, null pointer, etc.– IPC: Application-defined signals (USR1, USR2)– Control process execution (KILL, STOP, CONT) Send a signal using kill(pid, signo)– Killing an errant program is common, but you can alsosend a non-lethal signal using kill() Use signal() or sigaction() to set the handler for asignalCOMP 530: Operating SystemsHow signals work Although signals appear to be deliveredimmediately – They are actually delivered lazily – Whenever the OS happens to be returning to the processfrom an interrupt, system call, etc. So if I signal another process, the other process maynot receive it until it is scheduled again Does this matter?5

10/1/16COMP 530: Operating SystemsCOMP 530: Operating SystemsMore details When a process receives a signal, it is added to apending mask of pending signals– Stored in PCB Just before scheduling a process, the kernel checks ifthere are any pending signals– If so, return to the appropriate handler– Save the original register state for later– When handler is done, call sigreturn() system callMeta-lesson Laziness rules!– Not on homework– But in system design Procrastinating on work in the system often reducesoverall effort– Signals: Why context switch immediately when it willhappen soon enough? Then resume executionCOMP 530: Operating SystemsCOMP 530: Operating SystemsLanguage Exceptions Signals are the underlying mechanism for Exceptionsand catch blocks JVM or other runtime system sets signal handlers– Signal handler causes execution to jump to the catch blockWindows comparison Exceptions have specific upcalls from the kernel tontdll IPC is done using Events––––Shared between processesHandle in tableNo data, only 2 states: set and clearSeveral variants: e.g., auto-clear after checking the stateCOMP 530: Operating SystemsCOMP 530: Operating SystemsOutline Files and File HandlesInheritancePipesSocketsSignalsSynthesis Example: The ShellShell Recap Almost all ‘commands’ are really binaries– /bin/ls Key abstraction: Redirection over pipes– ‘ ’, ‘ ‘, and ‘ ’implemented by the shell itself6

10/1/16COMP 530: Operating SystemsA note on Lab 1Shell Example Ex: ls grep foo Shell pseudocde:COMP 530: Operating Systemsthshthshthshcshwhile(EOF ! read input) {wait()fork()fork()lsexec(ls)parse input();// Sets up chain of pipes// Forks and exec’s ‘ls’ and ‘grep’ separately// Wait on output from ‘grep’, print to console// print console prompt}thshcshlsexec(ls) You’re going to be creating lots of processes in thisassignment If you fork a process and it never terminates You’ve just created a Z O M B I E P R O C E S S!!– Zombie’s will fill up the process table in the Linux kernel– Nobody can create a new process– This means no one can launch a shell to kill the zombies!COMP 530: Operating SystemsA note on Lab 1thshwait()What about Ctrl-Z? Shell really uses select() to listen for new keystrokes– (while also listening for output from subprocess)fork()thshcshCOMP 530: Operating Systems Special keystrokes are intercepted, generate signalslsexec(ls) Be safe! Limit the number of processes you can create– add the command “limit maxproc 10” to the file /.cshrc– (remember to delete this line at the end of the course!) Periodically check for and KILL! zombie processes– Shell needs to keep its own “scheduler” for backgroundprocesses– Assigned simple numbers like 1, 2, 3 ‘fg 3’ causes shell to send a SIGCONT to suspendedchild– ps -ef egrep -e PID -e YOUR-LOGIN-NAME– kill pid-number Read the HW handout carefully for zombie-hunting details!COMP 530: Operating SystemsOther hints Splice(), tee(), and similar calls are useful forconnecting pipes together– Avoids copying data into and out-of applicationCOMP 530: Operating SystemsCollaboration Policy Reminder You can work alone or in a pair– Can be different from lab 0– Every line of code handed in must be written by one of thepair (or the boilerplate) No sharing code with other groups No code from Internet– Any other collaboration must be acknowledged in writing– High-level discussion is ok (no code) See written assignment and syllabus for more detailsNot following these rules is an Honor Code violation427

10/1/16COMP 530: Operating SystemsSummary Understand how handle tables work– Survey basic APIs Understand signaling abstraction– Intuition of how signals are delivered Be prepared to start writing your shell in lab 1!8

– If so, return to the appropriate handler – Save the original register state for later – When handler is done, call sigreturn() system call Then resume execution COMP 530: Operating Systems Meta-lesson Laziness rules! – Not on homework – But in system design Procrasti

Related Documents:

The Invisible Man Two Feet Up, Two Feet Down Up, Up, and Away: The Story of Amelia Earhart We Like to Play! What Am I? . Bats and Other Animals with Amazing Ears Bigfoot False! Popular Myths Debunked First on the Moon Haunted Places Jane Goodall . 530 530 530 530 530 530 530 530 530 530 530 530

The Invisible Man The Very Big Potato Two Feet Up, Two Feet Down Up, Up, and Away: The Story of Amelia Earhart . The Spider and the Beehive Weird Science: How Freaky Animals Got That Way . 530 530 530 530 530 530 530 540 540 540 540 540 540 540 550 550 550 550 550 550 550 550 550 550 55

goheels–draw an ASCII art Tar Heel Significant work –start early! 4. COMP 530: Operating Systems Outline . Application specifies a handler for each signal –OS provides default If a signal is received, control jumps to the handler . Then resume execution. COMP 530: O

Company Script Read-Through 300-530 SEPT 28 Music Everyone 300-530 SEPT 29 Dance, Head-shots, Acting Class 300-530 SEPT 30 NO REHEARSAL 1 2 SIGN UP FOR REMIND 3 ACTING Principals Only pg. 37-50 300-530 4 EARLY DISMISSAL NO REHEARSAL 5 Music Everyone 300-530 6 Dance Team 300-530 7 NO REHEARSA

Song of St. Patrick – Haugen – G Comp II # 685 Taste and See – Haugen – G Comp II # 34 Taste and See – Moore – G Comp II # 827 The Love of The Lord – Joncas – G Comp II # 680 The Servant Song – Richard Gillard– – G Comp II # 661 We Have Been Told – Haas – G Comp II # 69

2016-17 HERI Faculty Survey Institutional Profile Report Full-time Undergraduate Faculty Total Men Women CIRP Construct Note: Significance * p .05, ** p .01, *** p .001 Page 1 of 76 1A. American University of Beirut Your Inst Comp 1 Comp 2 Your Inst Comp 1 Comp 2 Your Inst Comp 1 Comp 2

12 530 02 38-77 1 fitting- fuel line 8 13 545 06 19-01 1 isolator filter housing 8 14 544 11 12-02 2 assy-oil/fuel cap w/ret. 8 15 530 01 59-06 2 screw m5.28x1.81x16mm plas 8 16 545 03 38-01 1 assy front isolator 8 17 577 54 06-01 1 rear isolator spring 8 18 530 09 56-46 1 assy- pick-up 19 530 02 11-06 1 line, fuel 8 20 530 01 58-14 1 screw .

Alex’s parents had been killed shortly after he was born and he had been brought up by his father’s brother, Ian Rider. Earlier this year, Ian Rider had died too, supposedly in a car accident. It had been the shock of Alex’s life to discover that his uncle was actually a spy and had been killed on a mission in Cornwall. That was when MI6 had