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 OutputTopicsTopicsI/O hardwareUnix file abstractionRobust I/OFile sharingio.pptCS 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 commandsVary from device to deviceDevice models can be very differentTape: read or write sequentially, or rewindDisk: “random” access at block levelTerminal: sequential, no rewind, must echo and allow editingVideo: write-only, with 2-dimensional structureOperating system should hide these differencesOperating system should hide these differences“Read” and “write” should work regardless of deviceSometimes 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 a file:Even the kernel is represented as a file:/dev/kmem (kernel memory image) /proc (kernel data structures)– 5 –CS 105Unix File TypesUnix File TypesRegular file: binary or text. Unix does not know the Regular file: binary or text. Unix does not know the difference!difference!Directory file: contains the names and locations of Directory file: contains the names and locations of other filesother filesCharacter special file: keyboard and network, for Character special file: keyboard and network, for exampleexampleBlock special file: like disks Block special file: like disks FIFO (named pipe): used for interprocess comunicationFIFO (named pipe): used for interprocess comunicationSocket: used for network communication between Socket: 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 simple interface called Unix I/Oexport simple interface called Unix I/OKey Unix idea: All input and output is handled in a Key Unix idea: 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 informs kernel that you are getting ready to access that Opening a file informs kernel that you are getting ready to access that filefileReturns a small identifying integer Returns a small identifying integer file descriptorfile descriptorfd == -1 indicates that an error occurred; errno has reasonstrerror 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 input1: standard output2: 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 bufbufnbytes == -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 position.then updates current file position.Returns number of bytes written from Returns number of bytes written from bufbuf to file to file fdfdnbytes == -1 indicates that an error occurredAs 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
View Full Document