CS 241 Springt 2007System Programming3/30/07 CS241 © 2007 LA, RHC and YZ, AllRights Reserved1File I/OCS 241 Lecture 27RR: Ch 4, 5 pp116-186Lawrence Angrave2path?Change directory:#include <unistd.h>int chdir(const char *path);Get the current directory char *getcwd(char *buf, size_t size);3ContentsLink demonstrationLevels of AccessFile System Tables (revisited)Open Close & Access ControlsSpecial FilesPipes & FIFO4Levels of Access Methods to FilesDisk BlockFile System Logical device – InodeFile System Symbolic device – FileOperating System Memory Mapped File5Levels of Access MethodsBlock devices in UnixLinux paths /dev/hda … is a block device for disk brw------- 1 angrave disk 3, 0 Oct 20 17:15 hdaBlock level access to a file is in terms of blocks orphysical records within a file/disk The user must do his own buffering. Access methodsinclude: Read(file, block_no) Write(file, block_no)6Levels of Access Methods ContinuedFile level access to the file is in terms of acquiring access to acopy of the file that is stored in primary memoryQueued or buffered level access to the file is in terms oflogical records that depend on software interpretation. Forexample, read and write, putc, getc characters in UNIX.Buffering is used to provide logical record abstraction andmaps i/o into physical recordsThese are all controlled by flags in open7Levels of Access Methods: MMAPmemory mapped file level the file is mapped into virtual memory file access is at the instruction level page faults may read a page of file data from disk to memory an address of a logical record within a file is given by a virtualmemory address offset of that record from the beginning of the fileAStackHeapATextVirtual MemoryDisk8ProtectionIn file systems, protection is needed from physicaldamage (reliability) and improper access(protection)Reliability is generally provided by duplicate copiesof data (or more sophisticaed redundancyschemes e.g. RAID)9ProtectionProtection - various mechanisms for single-usersystem and multi-user systems Removing the floppy disk, Prohibiting access to files of other users10Theory: Controlled Access operationsread - possible access to read from filewrite - possible access to write to a fileexecute - load file and execute itappend - write new information at the end of a filedelete - delete file and free its space for possible reuselist - list name and attributes of a file11Access Lists and GroupsAssociate each file and directory with access listProblem with access list: lengthSolution: condensed version of the access list owner - user who created the file group - a set of users who are sharing the file and need similaraccess universe - all other users12Access Lists ExampleUNIX - 3 fields of length 3 bits are used.user(u),group(g),others(o), bits are read(r),write(w), execute(x) -e.g.chmod go+rw myfile13Other Protection Approachesassociate a password with each file (XP)protect directories - listing of file names might be aprotected operation>mkdir dir>mkdir dir/passwordx>mkdir dir/passwordx/example>chmod 111 dir>cd dir>lsls: .: Permission denied>cd passwordx>lsexampleencryption14Implementation:File positionR/WPointer to inodeFile positionR/WPointer to inodeModeLink CountUIDGIDFile sizeTimesAddress of first 10 disk blocksSingle IndirectDouble IndirectTriple IndirectIn memoryInode tableOpen file descriptionParent File descriptortableChildFiledescriptortableUnrelated processFile descriptor tableSystem file table15Tables in kernel for filesFile Descriptor Table One per process- contains 32 entries 0 stdin, 1 stdout, 2 stderr + files, directories, block orcharacter devices (also called "special files"), sockets, FIFOs(also called named pipes), or unnamed pipes.System File Table One per system – is in kernel Contains file offset, access mode, count of file descriptorentries using it Several entries may correspond to one fileThe in-memory inode table has one entry for eachactive file.16Opening and Closing FilesOpen associates a file descriptor with a file orphysical deviceFile descriptor is an index into a table perprocess and can be inherited to childprocesses allowing sharingShould close open filesOflag access modes and status17Access Control sys/stat.hR W X R W X R W Xusergroup othersS_IRUSRS_IWUSRS_IXUSRS_IRWXUS_IRGRPS_IWGRPS_IXGRPS_IRWXGS_IROTHS_IWOTHS_IXOTHS_IRWXOS_ISUID – set user ID on executionS_ISGID – set group ID on execution18Additional OflagsO_APPEND – file offset to EOFO_CREAT – need to give permissionsO_EXCL – use with CREATE detects fileO_NOCTTY – prevents device from becomingcontrolling terminalO_NONBLOCK – return immediatelyO_TRUNC – file to beginning for write19File Access Exampleint fd;mode_t fdmode = (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);If ((fd = open(“info.dat”, O_RDWR | O_CREAT, fdmode)) == -1) perror(“Failed to open info.dat”);Opens a file info.dat in current directory rewriting any existing file dataif present.20Close#include <errno.h>#include <unistd.h>int r_close(int fd) { int retval; while (retval = close(fd), retval == -1 && errno == EINTR) ; return retval;}21SELECTMonitoring multiple files – use a process per file(recommended) or use theSelect statement – can select input from one of anumber of different files or return after timeoutint select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout);22SummaryFile System TablesOpen CloseFile Permissions/Access ControlNext: Buffering, Redirection, Pipes & FIFOs23File Pointers and BufferingISO C standard I/O Library uses file pointers notfile descriptors (p122) fopen(), fclose(), fread(), fwrite(), fseek fprintf, fscanf()fflush call empties buffer to deviceFiles associated with terminals are line buffered –ie not written out until buffer is full or newlinesymbol entered24Filters and RedirectionFilters in UNIX shell head, tail, more, cat sort, grep, awkRedirection uses < > Example: Redirect output to my.file cat >my.file How to implement redirection? First open my.file Copy the file descriptor return to standard output using:#include <unistd.h>int dup2(int fildes1, int fildes2);Copies file descriptor entry fildes1 to entry fildes225PipesPipe--- communication between two processes on the same machine find . –name “*.c” –print | grep cs241#include <unistd.h>int pipe(int fildes[2]);Creates 2 file descriptorsint fd[2];if (pipe(fd)
View Full Document