System Calls and Standard I/OGoals of Today’s ClassSystem CallsCommunicating With the OSProcessor ModesMain Categories of System CallsSlide 7Implementing a System CallMain UNIX System Calls for FilesExample: UNIX open() System CallExample: UNIX read() System CallStandard I/O LibrarySlide 13Layers of AbstractionStream AbstractionSequential Access to a StreamExample: Opening a FileExample: Formatted I/OExample: A Simple getchar()Making getchar() More EfficientBetter getchar() with Buffered I/ODetails of FILE in stdio.h (K&R 8.5)A Funny Thing About Buffered I/OChallenges of WritingSafe-Write CodeSummary of System Calls and Stdio1System Calls and Standard I/OProfessor Jennifer Rexfordhttp://www.cs.princeton.edu/~jrex2Goals of Today’s Class•System callsHow a user process contacts the Operating SystemFor advanced services that may require special privilege•Standard I/O libraryGeneric I/O support for C programsA smart wrapper around I/O-related system callsStream concept, line-by-line input, formatted output, ...3System Calls4Communicating With the OS•System callRequest to the operating system to perform a task… that the process does not have permission to perform•SignalAsynchronous notification sent to a process… to notify the process of an event that has occurred User ProcessOperating Systemsignals systems calls5Processor Modes•The OS must restrict what a user process can doWhat instructions can executeWhat portions of the address space are accessible•Supervisor mode (or kernel mode)Can execute any instructions in the instruction set–Including halting the processor, changing mode bit, initiating I/OCan access any memory location in the system–Including code and data in the OS address space•User modeRestricted capabilities–Cannot execute privileged instructions–Cannot directly reference code or data in OS address spaceAny such attempt results in a fatal “protection fault”–Instead, access OS code and data indirectly via system calls6Main Categories of System Calls•File systemLow-level file I/OE.g., creat, open, read, write, lseek, close•Multi-tasking mechanismsProcess controlE.g., fork, wait, exec, exit, signal, kill•Inter-process communicationE.g., pipe, dup, dup2•Unix has a few hundred system callsSee “man 2 intro” or /usr/include/syscall.h7System Calls•Method for user process to invoke OS services•Called just like a functionEssentially a “protected” function callThat transfers control to the OS and backFile Systemcreat, open, close,read, write, lseekApplicationOSUserProcess8Implementing a System Call •System calls are often implemented using trapsOS gains control through trapSwitches to supervisor modePerforms the serviceSwitches back to user modeGives control back to usermovl $1, %eaxint $0x80Which call?1: exit2: fork3: read4: write5: open6: close…Trap to the OSSystem-call specific arguments are put in registers9Main UNIX System Calls for Files•Creat: int creat(char *pathname, mode_t mode);Create a new file and assign a file descriptor•Open: int open(char *pathname, int flags, mode_t mode);Open the file pathname and return a file descriptor•Close: int close(int fd);Close a file descriptor fd•Read: int read(int fd, void *buf, int count);Read up to count bytes from fd, into the buffer at buf•Write: int write(int fd, void *buf, int count);Writes up to count bytes into fd, from the buffer at buf•Lseek: int lseek(int fd, int offset, int whence);Assigns the file pointer to a new value by applying an offset10Example: UNIX open() System Call•Converts a path name into a file descriptorint open(const char *pathname, int flags, mode_t mode);•ArgumentsPathname: name of the fileFlags: bit flags for O_RDONLY, O_WRONLY, O_RDWRMode: permissions to set if file must be created•ReturnsInteger file descriptor (or a -1 if an error)•Performs a variety of checksE.g., whether the process is entitled to access the file11Example: UNIX read() System Call•Reads data from an open fileint read(int fd, void *buf, int count);•ArgumentsFile descriptor: integer descriptor returned by open()Buffer: pointer to memory to store the bytes it readsCount: maximum number of bytes to read•ReturnsNumber of bytes read–Value of 0 if nothing more to read–Value of -1 if an error•Performs a variety of checksWhether file has been opened, whether reading is okay12Standard I/O Library13Standard I/O Library•PortabilityGeneric I/O support for C programsSpecific implementations for various host OSesInvokes the OS-specific system calls for I/O•Abstractions for C programsStreamsLine-by-line inputFormatted output •Additional optimizationsBuffered I/OSafe writingFile SystemStdio LibraryAppl ProguserOS14Layers of AbstractionDiskDriverStorageFile Systemdisk blocksvariable-length segmentshierarchical file systemOperatingSystemStdio LibraryFILE * streamAppl ProgUserprocessint fd15Stream Abstraction•Any source of input or destination for outputE.g., keyboard as input, and screen as outputE.g., files on disk or CD, network ports, printer port, …•Accessed in C programs through file pointersE.g., FILE *fp1, *fp2;E.g., fp1 = fopen(“myfile.txt”, “r”);•Three streams provided by stdio.hStreams stdin, stdout, and stderr–Typically map to keyboard, screen, and screenCan redirect to correspond to other streams–E.g., stdin can be the output of another program–E.g., stdout can be the input to another program16Sequential Access to a Stream•Each stream has an associated file positionStarting at beginning of file (if opened to read or write)Or, starting at end of file (if opened to append)•Read/write operations advance the file positionAllows sequencing through the file in sequential manner•Support for random access to the streamFunctions to learn current position and seek to new onefile file17Example: Opening a File •FILE *fopen(“myfile.txt”, “r”)Open the named file and return a streamIncludes a mode, such as “r” for read or “w” for write•Creates a FILE data structure for the fileFile descriptor, mode, status, buffer, …Assigns fields and returns a pointer•Opens or creates the file, based on the modeWrite (‘w’): create file with default permissionsRead (‘r’): open the file as read-onlyAppend
View Full Document