Lecture 14. Shell. File descriptors. File table and descriptors. Fork and exec Fd manipulation Pipes

Similar documents
CS 25200: Systems Programming. Lecture 14: Files, Fork, and Pipes

CS 25200: Systems Programming. Lecture 16: Wildcards

Process Creation in UNIX

Process Management 1

Lecture 2: Kernels and Processes

Process Management! Goals of this Lecture!

Contents. IPC (Inter-Process Communication) Representation of open files in kernel I/O redirection Anonymous Pipe Named Pipe (FIFO)

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

everything is a file main.c a.out /dev/sda1 /dev/tty2 /proc/cpuinfo file descriptor int

CSC209H Lecture 6. Dan Zingaro. February 11, 2015

File Descriptors and Piping

Outline. Relationship between file descriptors and open files

Process Management! Goals of this Lecture!

Pipes and FIFOs. Woo-Yeong Jeong Computer Systems Laboratory Sungkyunkwan University

CS 11 C track: lecture 1

Recitation 8: Tshlab + VM

CS240: Programming in C

. Written in factored form it is easy to see that the roots are 2, 2, i,

CSE 410: Systems Programming

Input and Output System Calls

UNIX System Programming. Overview. 1. A UNIX System. 2. Processes (review) 2.1. Context. Pipes/FIFOs

Processes. Processes (cont d)

Contents. PA1 review and introduction to PA2. IPC (Inter-Process Communication) Exercise. I/O redirection Pipes FIFOs

IC221: Systems Programming 12-Week Written Exam [SOLUTIONS]

UNIX System Calls. Sys Calls versus Library Func

CSC209H Lecture 7. Dan Zingaro. February 25, 2015

CMPT 125 Assignment 2 Solutions

628 Lecture Notes Week 4

Systems Programming. COSC Software Tools. Systems Programming. High-Level vs. Low-Level. High-Level vs. Low-Level.

UNIX. Session 2. UNIX processes and forking fork system call exec system call death of process kill fork and I/O using it UNIX.

OS COMPONENTS OVERVIEW OF UNIX FILE I/O. CS124 Operating Systems Fall , Lecture 2

Exercise 6 (Week 42) For the foreign students only.

CSC 1600 Unix Processes. Goals of This Lecture

SOFTWARE ARCHITECTURE 3. SHELL

The Shell, System Calls, Processes, and Basic Inter-Process Communication

Operating System Labs. Yuanbin Wu

Pipelines, Forks, and Shell

Processes COMPSCI 386

CS 25200: Systems Programming. Lecture 11: *nix Commands and Shell Internals

Inter-Process Communication

Lecture 28: Data Link Layer

Computer Science 330 Operating Systems Siena College Spring Lab 5: Unix Systems Programming Due: 4:00 PM, Wednesday, February 29, 2012

CSE 410: Systems Programming

CSE 333 SECTION 3. POSIX I/O Functions

Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

System Programming. Pipes I

CS240: Programming in C

IPC and Unix Special Files

The Idea. Leader Election. Outline. Why Rings? Network. We study leader election in rings. Specification of Leader Election YAIR. Historical reasons

프로세스간통신 (Interprocess communication) i 숙명여대창병모

Chapter 3 Processes we will completely ignore threads today

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

Inter-process Communication using Pipes

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

Preview. Interprocess Communication with Pipe. Pipe from the Parent to the child Pipe from the child to the parent FIFO popen() with r Popen() with w

Hyo-bong Son Computer Systems Laboratory Sungkyunkwan University

COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen

Operating Systems. Lecture 06. System Calls (Exec, Open, Read, Write) Inter-process Communication in Unix/Linux (PIPE), Use of PIPE on command line

Interprocess Communication E. Im

Maria Hybinette, UGA. ! One easy way to communicate is to use files. ! File descriptors. 3 Maria Hybinette, UGA. ! Simple example: who sort

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

Processes. Operating System CS 217. Supports virtual machines. Provides services: User Process. User Process. OS Kernel. Hardware

Chapter 4 Threads. Operating Systems: Internals and Design Principles. Ninth Edition By William Stallings

Package RcppRoll. December 22, 2014

Lecture 23: System-Level I/O

Processes often need to communicate. CSCB09: Software Tools and Systems Programming. Solution: Pipes. Recall: I/O mechanisms in C

Naked C Lecture 6. File Operations and System Calls

CIS 121. Introduction to Trees

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

CS 111: Program Design I Lecture 15: Objects, Pandas, Modules. Robert H. Sloan & Richard Warner University of Illinois at Chicago October 13, 2016

Threads and Concurrency in Java: Part 2

Python Programming: An Introduction to Computer Science

System- Level I/O. Andrew Case. Slides adapted from Jinyang Li, Randy Bryant and Dave O Hallaron

Processes. Non-examples (implemented as one process): Why processes? - emacs text editor - firefox web browser

Unix Basics Compiling and Using. CMPT 300 Operating Systems I Summer Segment 2: Unix Basics. Melissa O Neill

Basic OS Progamming Abstrac7ons

Basic OS Progamming Abstrac2ons

ESE 333 Real-Time Operating Systems 2 What is an operating system? Two views: 1. Top-down view: Extended machine ffl Covers the details of the hardwar

System Calls and Signals: Communication with the OS. System Call. strace./hello. Kernel. Context Switch

COMP 2355 Introduction to Systems Programming

Chapter 24. Sorting. Objectives. 1. To study and analyze time efficiency of various sorting algorithms

Figure 1 Ring Structures

CS 201. Files and I/O. Gerson Robboy Portland State University

why study sorting? Sorting is a classic subject in computer science. There are three reasons for studying sorting algorithms.

15-859E: Advanced Algorithms CMU, Spring 2015 Lecture #2: Randomized MST and MST Verification January 14, 2015

Administrivia. No credit for late assignments w/o extension Ask cs140-staff for extension if you can t finish

Section 2: Processes

Implementation of a simple shell, xssh

CS240: Programming in C

Basic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.

The Magma Database file formats

UNIX I/O. Computer Systems: A Programmer's Perspective, Randal E. Bryant and David R. O'Hallaron Prentice Hall, 3 rd edition, 2016, Chapter 10

CMSC Computer Architecture Lecture 10: Caches. Prof. Yanjing Li University of Chicago

Unix-Linux 2. Unix is supposed to leave room in the process table for a superuser process that could be used to kill errant processes.

UNIX input and output

CSE 333 SECTION 3. POSIX I/O Functions

10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output

CS 3113 Introduction to Operating Systems Midterm October 11, 2018

CS 3113 Introduction to Operating Systems Midterm October 11, 2018

Transcription:

218 Dr. Jeffrey A. Turkstra 1 Lecture 14 File table ad descriptors CS 252: Systems Programmig Lecture 14: Files, Fork, ad Pipes Fork ad exec Fd maipulatio Pipes Dr. Jef Turkstra 218 Dr. Jeffrey A. Turkstra 2 Lexer shell.l ls -al a* grep me > fle1 <ls> <-al> <a*> <PIPE> <grep> <me> <GREAT> <fle1> Shell Parser shell.y wildcards ev vars ls -al a* grep me I:dft Out:fle1 Err:dft ls -al aab aaa grep Commad Table Fial Commad Table me I:dft Out:fle1 Err:dft executor File descriptors Ope fles, pipes, etwork sockets are referred to by a iteger value called the file descriptor or fd This value is a idex ito a fle descriptor table maitaied i the kerel Caot be directly maipulated by a process 218 Dr. Jeffrey A. Turkstra 3 218 Dr. Jeffrey A. Turkstra 4 fd File descriptors ca be viewed i a umber of ways $ lsof $ ls /proc/pid/fd Most processes will have three default fds: stdi, 1 stdout, ad 2 stderr Dictated by POSIX referece cout 1 O_WRONLY O_APPEND O_SYNC fctl() ca be used to maipulate fd fags ad status fags 218 Dr. Jeffrey A. Turkstra 5 218 Dr. Jeffrey A. Turkstra 6

218 Dr. Jeffrey A. Turkstra 7 Ope fle object Holds most of a fle s state Poiter to a iode (really a vode) Access mode (OeRDONLY, OeRDWR, OeWRONLY) Status fags (OeASYNC, OeAPPEND, OeNONBLOCK, etc) Ofset where the ext read or write operatio will commece Referece cout similar to iodes ope() system call it ope(cost char *pathame, it flags[, mode_t mode]); Flags icludes: Access mode (OeRDONLY, OeWRONLY, OeRDRWR) required File creatio fags (OeCLOEXEC, OeCREAT, OeTRUNC, etc) optioal File status fags (OeAPPEND, OeSYNC, OeNONBLOCK, etc) Mode is your usual fle creatio mode 218 Dr. Jeffrey A. Turkstra 8 close() system call it close(it fd); Decremets the referece cout for the appropriate ope fle object Object is reclaimed if referece cout == Returs -1 o error ad sets erro Failig to close() fds results i a fle descriptor leak Arguably worse tha a memory leak erro Whe system call wrappers retur -1, they usually set a global variable erro. #iclude <erro.h> 218 Dr. Jeffrey A. Turkstra 9 218 Dr. Jeffrey A. Turkstra 1 fork() system call pid_t fork(void); Wrapper for the cloe system call Do t worry about this too much The oly way to create a ew process i *ix Creates a idetical copy of the curretly ruig process Copy-o-write optimizatio avoids the overhead of duplicatig memory fork() it New process is a child of the paret process Ope fle descriptor table is copied Ope fle objects are shared Referece cout is icreased by oe 218 Dr. Jeffrey A. Turkstra 11 218 Dr. Jeffrey A. Turkstra 12

218 Dr. Jeffrey A. Turkstra 13 After fork() Shared fle_t Paret fdtable Child fdtable O_WRONLY O_APPEND O_SYNC referece cout 2 We ca use our shared fle objects to establish a commuicatio chael betwee the paret ad child Or eve amog multiple childre Note: Solaris does t share the fle positio This ca cause headaches betwee platforms 218 Dr. Jeffrey A. Turkstra 14 Executig somethig else What if what we wat to execute is ot part of our program? What if it is somewhere else? execve()! execvp() system call it execvp(cost char *file, char *cost argv[]); Replaces the curret process image with a ew process image Really wraps execve() execvp() eve searches $PATH for the executable, if o path provided Remember, argv must ed with a NULL! Successful execve() s ever retur 218 Dr. Jeffrey A. Turkstra 15 218 Dr. Jeffrey A. Turkstra 16 void mai() { // Create a ew process it ret = fork(); if (ret == ) { // Child process: execute ls al cost char *argv[3]; argv[] = ls ; argv[1] = -al ; argv[2] = NULL; execvp(argv[], argv); // There was a error perror( execvp ); else if (ret < ) { // There was a error i fork perror( fork ); exit(2); else { // This is the paret process // ret is the pid of the child // Wait util the child exits waitpid(ret, NULL,); // ed if exit(); // No error // ed mai 218 Dr. Jeffrey A. Turkstra 17 Our shell Commad::execute() { it ret; for (it i = ; i < _umberofsimplecommads; i++) { ret = fork(); if (ret == ) { //child execvp(scom[i]->_args[], scom[i]->_args); perror( execvp ); else if (ret < ) { perror( fork ); retur; // Paret shell cotiue // for if (!backgroud) { // wait for last process waitpid(ret, NULL); // execute 218 Dr. Jeffrey A. Turkstra 18

218 Dr. Jeffrey A. Turkstra 19 dup2() system call it dup2(it oldfd, it ewfd); Creates a copy of the fle descriptor usig the provided ewfd ewfd will be siletly closed if it is already ope! Ad it s atomic! 2 FD_CLOEXEC dup2(2, 1); O_WRONLY O_APPEND O_SYNC referece cout 2 218 Dr. Jeffrey A. Turkstra 2 Redirectig stdout it mai(it argc,char**argv) { // Create a ew file it fd = ope( myoutput.txt, O_CREAT O_WRONLY O_TRUNC, 664); if (fd < ) { perror( ope ); // Redirect stdout to file dup2(fd,1); close(fd); // fd o loger eeded. dup() system call it dup(it oldfd); Creates a copy of the fle descriptor usig the ext available fd Hady if you wat to save a fd for some reaso Hmmmm // Now pritf that prits to stdout, will write to // myoutput.txt pritf( Hello world\ ); 218 Dr. Jeffrey A. Turkstra 21 218 Dr. Jeffrey A. Turkstra 22 pipe() system call it pipe(it pipefd[2], it flags); Creates a uidirectioal data chael Two fle descriptors pipefd[]: read ed pipefd[1]: write ed There is kerel buferig Flags are optioal OeNONBLOCK, OeCLOEXEC, etc Solaris has bidrectioal pipes 218 Dr. Jeffrey A. Turkstra 23 3 4 it fds[2]; pipe(fds); fdpipe[] == 3 fdpipe[1] == 4 Pipe dream offset referece cout 1 offset referece cout 1 O_WRONLY O_RDONLY 218 Dr. Jeffrey A. Turkstra 24

218 Dr. Jeffrey A. Turkstra 25 lsgrep it mai(it argc,char**argv) { if (argc < 3) { fpritf(stderr, "usage: lsgrep arg1 arg2\"); // Strategy: paret does the redirectio before fork() save stdi/stdout it tempi = dup(); it tempout = dup(1); // create pipe it fdpipe[2]; pipe(fdpipe); //redirect stdout for "ls dup2(fdpipe[1],1); close(fdpipe[1]); // fork for "ls it ret= fork(); if (ret==) { // close file descriptors as soo as are ot eeded close(fdpipe[]); char *args[3]; args[]="ls"; args[1]= -al"; args[2]=null; execvp(args[], args); // error i execvp perror("execvp"); //redirectio for "grep // redirect stdi dup2(fdpipe[], ); close(fdpipe[]); //create outfile it fd=ope(argv[2], O_WRONLY O_CREAT O_TRUNC, 6); if (fd < ){ perror("ope"); //redirect stdout dup2(fd,1); close(fd); // fork for grep ret= fork(); if(ret==) { char * args[3]; args[]= grep"; args[1]=argv[1]; args[2]=null; execvp(args[], args); // error i execvp perror("execvp"); _ 218 Dr. Jeffrey A. Turkstra 26 Questios? // Restore stdi/stdout dup2(tempi,); dup2(tempout,1); close(tempi); close(tempout); // Paret waits for grep process waitpid(ret,null,); pritf( All doe!!\ ); // mai 218 Dr. Jeffrey A. Turkstra 27 218 Dr. Jeffrey A. Turkstra 28