Harvey Mudd CS 105 - Input and Output

Unformatted text preview:

Input and OutputI/O: A Typical Hardware SystemAbstracting I/OUnix FilesUnix File TypesUnix I/OOpening FilesClosing FilesReading FilesWriting FilesSimple ExampleDealing with Short Counts“Foolproof” I/OImplementation of rio_readnUnbuffered I/OBuffered InputBuffered ExampleI/O ChoicesI/O Choices, continuedHow the Unix Kernel Represents Open FilesFile SharingHow Processes Share FilesI/O RedirectionFile MetadataSummary: Goals of Unix I/OInput and OutputInput and OutputTopicsTopicsI/O hardwareUnix file abstractionRobust I/OFile sharingCS 105“Tour of the Black Holes of Computing”– 2 –CS 105I/O: A Typical Hardware SystemI/O: A Typical Hardware SystemmainmemoryI/O bridgebus interfaceALUregister fileCPU chipsystem bus memory busdisk controllergraphicsadapterUSBcontrollermousekeyboard monitordiskI/O busExpansion slots forother devices suchas network adapters.– 3 –CS 105Abstracting I/OAbstracting I/OLow level requires complex device commandsLow level requires complex device commandsVary from device to deviceDevice models can be very differentTape: read or write sequentially, or rewindDisk: “random” access at block levelTerminal: sequential, no rewind, must echo and allow editingVideo: write-only, with 2-dimensional structureOperating system should hide these differencesOperating system should hide these differences“Read” and “write” should work regardless of deviceSometimes impossible to generalize (e.g., video)Still need access to full power of hardware– 4 –CS 105Unix FilesUnix FilesA Unix A Unix filefile is a sequence of is a sequence of mm bytes: bytes:B0, B1, .... , Bk , .... , Bm-1All I/O devices are represented as files:All I/O devices are represented as files:/dev/sda2 (/usr disk partition)/dev/tty2 (terminal)Even the kernel is represented as files:Even the kernel is represented as files:/dev/kmem (kernel memory image) /proc (kernel data structures)– 5 –CS 105Unix File TypesUnix File TypesRegular fileRegular file: binary or text. Unix does not know the : binary or text. Unix does not know the difference!difference!DirectoryDirectory: contains the names and locations of other : contains the names and locations of other filesfilesCharacter special fileCharacter special file: keyboard and network, for : keyboard and network, for exampleexampleBlock special fileBlock special file: like disks : like disks FIFOFIFO (named pipe): used for interprocess comunication (named pipe): used for interprocess comunicationSocketSocket: used for network communication between : used for network communication between processesprocesses– 6 –CS 105Unix I/OUnix I/OThe elegant mapping of files to devices allows kernel to The elegant mapping of files to devices allows kernel to export a simple interface called Unix I/Oexport a simple interface called Unix I/OKey Unix ideaKey Unix idea: All input and output is handled in a : All input and output is handled in a consistent and uniform wayconsistent and uniform wayBasic Unix I/O operations (system calls): Basic Unix I/O operations (system calls): Opening and closing files: open()and close()Changing the current file position (seek): llseek (not discussed)Reading and writing a file: read() and write()– 7 –CS 105Opening FilesOpening FilesOpening a file tells kernel you are getting ready to access itOpening a file tells kernel you are getting ready to access itReturns small identifying integer Returns small identifying integer file descriptorfile descriptorfd == -1 indicates that an error occurred; errno has reasonstrerror converts to English (Note: use strerror_r for thread safety)Each process created by a Unix shell begins life with three open files Each process created by a Unix shell begins life with three open files (normally connected to terminal):(normally connected to terminal):0: standard input1: standard output2: standard errorint fd; /* file descriptor */if ((fd = open(“/etc/hosts”, O_RDONLY)) == -1) { fprintf(stderr, “Couldn’t open /etc/hosts: %s”, strerror(errno)); exit(1);}– 8 –CS 105Closing FilesClosing FilesClosing a file tells kernel that you’re finished with itClosing a file tells kernel that you’re finished with itClosing an already closed file is recipe for disaster in Closing an already closed file is recipe for disaster in threaded programs (more on this later)threaded programs (more on this later)Some error reports are delayed until close!Some error reports are delayed until close!Moral: Always check return codes, even for seemingly Moral: Always check return codes, even for seemingly benign functions such as benign functions such as close()close()perrorperror is simplified is simplified strerror/fprintfstrerror/fprintf; see man page; see man pageint fd; /* file descriptor */int retval; /* return value */if ((retval = close(fd)) == -1) { perror(“close”); exit(1);}– 9 –CS 105Reading FilesReading FilesReading a file copies bytes from current file position to memory, then Reading a file copies bytes from current file position to memory, then updates file positionupdates file positionReturns number of bytes read from file Returns number of bytes read from file fdfd into into bufbufnbytes == -1 indicates error occurred; 0 indicates end of file (EOF)short counts (nbytes < sizeof(buf) ) are possible and are not errors!char buf[4096];int fd; /* file descriptor */unsigned int nbytes; /* number of bytes read *//* Open file fd ... *//* Then read up to 4096 bytes from file fd */if ((nbytes = read(fd, buf, sizeof(buf))) == -1) { perror(“read”); exit(1);}– 10 –CS 105Writing FilesWriting FilesWriting a file copies bytes from memory to current file position, Writing a file copies bytes from memory to current file position, then updates current file positionthen updates current file positionReturns number of bytes written from Returns number of bytes written from bufbuf to file to file fdfdnbytes == -1 indicates that an error occurredAs with reads, short counts are possible and are not errors!Here, transfers up to 4096 bytes from address Here, transfers up to 4096 bytes from address bufbuf to file to file fdfdchar buf[4096];int fd; /* file descriptor */unsigned int nbytes; /* number of bytes read *//* Open the file fd ... *//* Then write up to 4096 bytes from buf to file fd */if ((nbytes = write(fd, buf,


View Full Document

Harvey Mudd CS 105 - Input and Output

Documents in this Course
Processes

Processes

25 pages

Processes

Processes

27 pages

Load more
Download Input and Output
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Input and Output and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Input and Output 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?