Top Banner

of 32

Files and Directories

Jan 10, 2016

Download

Documents

Unix Files and Directories
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • Files and DirectoriesFile typesstat functions for file informationFile permissionssuid and sgidSticky bitHard link and soft linkDirectory operationsDevice special filesFile system

  • File TypesRegular fileDirectory fileCharacter special file (unbuffered I/O access)Block special file (buffered I/O)Named Pipe (a type of IPC) - FIFOSocket (a network form of IPC)Symbolic Link (a file that just points to another file)

  • stat, fstat and lstatint stat(const char *path, struct stat *buf);int fstat(int filedes, struct stat *buf);int lstat(const char *path, struct stat *buf);All three return 0 on success or -1 on failureAll three set buf to point to a structure of informationstat get info about the filefstat gets info about an already open filelstat same as stat but if given a symbolic link will get info about the link instead of what the link points to

  • stat structureDefinition on page 88st_modest_inost_devst_rdevst_nlinkst_uidst_gid

    st_sizest_blocksst_blksizest_atimest_mtimest_ctime

  • Determining the type of a fileSet of macros defined in can be used.They all accept the st_mode field of the stat struct as their only parameterS_ISREG(mode_t mode)S_ISDIR(mode_t mode)S_ISCHR(mode_t mode)S_ISBLK(mode_t mode)S_ISFIFO(mode_t mode)S_ISLNK(mode_t mode)S_ISSOCK(mode_t mode)

  • Set-User-ID & Set-Group-IDEvery process has 6 or more IDsReal user IDReal group IDEffective user IDEffective group IDSupplementary group IDsSaved set-user-IDSaved set-group-ID

  • Set-User-ID & Set-Group-IDNormally, effective IDs are the same as real user IDsSometimes, we need to run a process with the permissions of the user or group that owns the file (ex: passwd)Two bits in the files mode word (st_mode) allow this.set-user-ID bitset-group-ID bit

  • Set-User-ID & Set-Group-IDWhen creating a file with the creat function, the new files UID is the effective UID of the process, and the new files GID is the effective GID of the process

  • Checking set-user-ID and set-group-ID bitsCan use S_ISUID and S_ISGID masksEx:if(S_ISUID & st_mode)if(S_ISGID & st_mode)

  • Setting SUID and GUIDSUID has a value of 4GUID has a value of 2chmod 4755 afile -rwsr-xr-xchmod 2755 afile -rwxr-sr-xchmod 6755 afile -rwsr-sr-x

  • File access permissionsRead section 4.5 on page 92. Note the different permissions required for operations on regular files versus directories

  • access functionTests to see if the real user ID and real group ID allow access to a fileUseful if a program that may be running as another user (ex root) wants to be sure that the person that started the program has permissions to access some fileint access(const char *pathname, int mode);Returns 0 if ok, -1 otherwise

  • access function (cont)In this context, mode is not the same as in previous functions. Here, mode is the bitwise OR of several constantsR_OK - test for read permissionW_OK - test for write permissionX_OK - test for execute permissionF_OK - test for file existence

  • umask functionmode_t umask(mode_t mask);Sets the file mode creation maskfile mode creation mask is used to specify the default permissions of newly created filesSince we are dealing with a mask it is the complement of what we want. So we set the bits corresponding to the permissions we dont want.

  • umask functionWhen using open or creat, any bits in mode that are also set in the file creation mask are turned off.All the UNIX shells also define a shell command called umask that displays the default umask set at login. Each process can change its own mask without interfering with each other

  • File Sizest_size member of stat structure holds the size of a fileOnly meaningful for regular files, directories and symbolic linksRegular file number of bytes in the fileDirectories multiple of a number (more on this later)Symbolic Links number of chars in filename

  • Sticky BitHistoricallyUsed to tell the system to keep a copy of the text portion of a program in the swap space even after the program exits. (text = instructions, not data)Swap file is contiguous faster start on next execution.

  • Sticky BitCurrentlyUsed on directories, indicates that in order to rename or delete a file in that directory a user must both have write permissions to the directory and one of the following must be trueUser owns the fileUser owns the directoryUser is the superuserTo set the sticky bitchmod +t mydir

  • chmod and fchmodAllows us to change the existing permissions for a fileint chmod(const char *path, mode_t mode);int fchmod(int fildes, mode_t mode);Returns 0 on success or -1 on failuremode is bitwise OR of constants shown on page 99 fig 4.11Effective UID of process must be the same as the UID of the file or the process must have superuser permissions

  • link, unlink, remove and renamelink int link(const char *oldpath, const char *newpath);Creates a new hard link within the file systemoldpath is the file to be linked. Newpath must already exist except for the last portion which will be createdIf all of newpath already exists, an error will be returnedReturns 0 if ok, -1 otherwise

  • link, unlink, remove and renameunlink int unlink(const char *pathname);Removes directory entry indicated by pathname Decrements the link count of the fileMust have write and execute on containing directoryOnly when link count reaches 0 and no process has the file open will it be deleted

  • link, unlink, remove and renameremove int remove(const char *pathname);Calls unlink for files and rmdir for directoriesrename int rename(const char *oldpath, const char *newpath);Equivelant to mv shell command

  • Symbolic LinksIndirect pointer to a file or directoryCreated to get around limitations of hard linksHard links must live in the same file system that the think it links to is inOnly superuser can hard link to a directory

  • symlink and readlinksymlink int symlink(const char *oldpath, const char *newpath);Creates the symbolic link file newpath that contains the text contained in oldpatholdpath and newpath may be on different file systemsreadlink ssize_t readlink(const char *path, char *buf, size_t bufsiz);open function follows symbolic links. readlink operates on the link file itselfString from file placed in buf, with number of bytes in bufsiz. String is not null terminated

  • File Times3 times are kept for any fileLast access timeLast modified timeLast status change timeThese are stored in the following fields of the stat structst_atimest_mtimest_ctime

  • utimeint utime(const char *filename, const struct utimbuf *buf);struct utimbuf { time_t actime; time_t modtime;}actime and modtime are calendar times marking seconds since Epochbuf may be NULL, in which case the time is updated to current system timeUnless using NULL for buf, just having write permissions is not enough. Effective user ID must equal owner ID or process must have superuser privileges

  • Directory Operationsmkdir and rmdir int mkdir(const char *pathname, mode_t mode); int rmdir(const char *pathname);Create and remove the specified directoryFor mkdir, the mode parameter is the same as those used for open. However, recall that interactions with the umask may occur!When creating directories, remember that we usually want execute permissions so that the files within the directory can be listed

  • Reading DirectoriesDIR *opendir(const char *name);struct dirent *readdir(DIR *dir);void rewinddir(DIR *dir);int closedir(DIR *dir);off_t telldir(DIR *dir);void seekdir(DIR *dir, off_t offset);

    struct dirent { ino_t d_ino; char d_name[NAME_MAX + 1];}

  • chdir fchdir and getcwdint chdir(const char *path);int fchdir(int fd);Change the current working directory of the processlong getcwd(char *buf, unsigned long size);Get the current working directory of the process

  • Device Special FilesMany devices are represented as files within /dev directoryEach device has major number and minor number for the Kernel to identify itMajor number usually specifies the driver to use for the deviceMinor number may be the specific sub device or options for that device

  • Device Special Filesls lL on a device file will show major and minor numbers instead of size of filest_dev and st_rdevst_dev for every file is the device number under the filesystem containing that filename and its associated i-nodest_rdev (only for character and block special files) contains actual device number

  • Device Special FilesObtaining the major and minor numbersUse the major and minor macrosmajor(st_dev)minor(st_dev)For block and character special devices use st_rdev instead to obtain real device number

    ****st_mode file type and mode (permissions)st_ino - i-node number (serial number)st_dev - device numberst_rdev - device number for special files st_nlink - number of linksst_uid - user id of ownerst_gid - group id of ownerst_size - number of bytes (for regular files)st_blocks number of disk blocks allocatedst_blksize best I/O block sizest_atime - time of last accessst_mtime - time of last modificationst_ctime - time of last file status change*

    Example code on page 90, fig 4.3Similar program http://www.cs.uah.edu/~kkeen/CS590/examples/filesanddirs/lstat/lstatexample.c*

    Green IDs of the account that starts the process. Usually taken from login information such as that defined in /etc/passwd fileBlue used for file access permission checksRed previous effective UID and GID saved by the exec function*

    Setting the set-user-ID bit will cause the effective UID to be the same as st_uid (owner of the file)Setting the set-group-ID bit will cause the effective GID to be the same as st_gid (owning group of the file)***

    Execute permission must be set for the associated SUID and GUID bits to have any effect.***

    Example: http://www.cs.uah.edu/~kkeen/CS590/examples/filesanddirs/access/accessexample.c

    **

    http://www.cs.uah.edu/~kkeen/CS590/examples/filesanddirs/umask/umaskexample.c*

    Symbolic link no ending null byte on filename because we know the size from st_size**

    This is useful for directories where everyone has permissions to create files, but only the owners of files should be able to delete them.**

    A hard link looks like another regular file that actually points to the same data. What really happens is that a new entry is put into the directory that points to the same i-node as the original file. Thus, we have two filenames that are really one file.

    Every file keep track of the number of hard links that refer to it. This data is stored in the st_nlink field of the stat struct

    Ex: link(/home/bob/data.txt, /home/joe/foo.txt);/home/joe must already exist, and foo.txt will be created. If foo.txt already exists in that directory, an error will be returned.*

    Also, if sticky bit is set on the directory we must eitherOwn the fileOwn the directoryHave superuser privileges

    Because a file is not truly removed while a process has it open, this makes unlink very useful for temporary files a process may need to create. The process can create the file, and immediately unlink it so that if the process crashes, the temp file will automatically be removed.

    If pathname is a symbolic link, the symbolic link will be removed, not the file it points to*

    superuser can call unlink on a directory, but really should use rmdir instead**

    Readlink returns number of bytes read if ok, or -1 otherwise*

    The ls shell command can display sorted by any of these three times. The default time display is last modified.ls lu can display the last access timels lc can display the last status change time

    Examples of operations that would effect the various times:Access time: readModification time: writeStatus change time: chmod, chown (basically anything that changes the files i-node)*Requires

    Epoch: 00:00:00 January 1st 1970 UTC (aka GMT)

    touch uses utime on some implementationsSome backup programs use utime when restoring files to set the date of the newly restored file back to the original date

    http://www.cs.uah.edu/~kkeen/CS590/examples/filesanddirs/utime/utimeexample.c**

    The dirent struct contains information about individual files in that directory. At a minimum it must contain the file name and i-node number of the associated file.

    These functions require #include *

    http://www.cs.uah.edu/~kkeen/CS590/examples/filesanddirs/getcwd/getcwdexample.c*

    Example: For file systems, the same driver (major number) would be used for a single disk, but the various file systems would have different minor numbers.

    *

    Capitol L option to ls says to follow symbolic links*

    http://www.cs.uah.edu/~keen/CS590/filesanddirs/device/devexample.c