CHAPTER 4. FILES AND DIRECTORIES System Programming 本份投影片大量參考熊博安教授的系統程式投影片 羅習五 國立中正大學資訊工程學系 EA-001 (05) ext Office: EA-517
Introduction Features of filesystem Properties of a file stat() fstat() lstat() Symbolic links Descending directory hierarchy Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 2
stat(), fstat(), lstat() 1.#include 2.int stat(const char *restrict pathname, struct stat *restrict buf); 3.int fstat(int filedes, struct stat *restrict buf); 1.int lstat(const char *restrict pathname, struct stat *restrict buf); Return: 0 if OK, -1 on error Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 3
restrict (c99 standard) “In C99, restrict is a keyword that can be used in pointer declarations. This limits the effects of pointer aliasing, aiding caching optimizations.” Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 4
restrict (c99 standard) void updatePtrs(size_t *restrict ptrA, size_t *restrict ptrB); the compiler is allowed to assume that ptrA and ptrB point to different locations and updating one pointer will not affect the other pointers. Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 5
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 6 stat(), fstat(), lstat() stat() returns a structure of information about a named file fstat() returns information about a file that is already open on descriptor filedes lstat() returns information about symbolic link
struct stat 1.struct stat { 2.mode_t st_mode;/* file type & mode */ 3.ino_t st_ino; /* i-node # */ 4.dev_t st_dev; /* device # */ 5.dev_t st_rdev; /* device # for special file */ 6.nlink_t st_nlink;/* # of links */ 7.uid_t st_uid; /* owner UID (user ID) */ 8.gid_t st_gid; /* owner GID (group ID) */ 9.off_t st_size; /* size in bytes, for regular files */ 10.time_t st_atime;/* time of last access */ 11.time_t st_mtime;/* time of last modification */ 12.time_t st_ctime;/* time of last file status change */ 13.blksize_t st_blksize;/* best I/O block size */ 14.blkcnt_t st_blocks;/* # disk blocks allocated */ 15.}; Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 7
File Types Regular file: contains data, interpretation left to application program Directory file: contains names of other files and pointers to information on these files Block special file: A type of file providing buffered I/O access in fixed-size units to devices such as disk drives. Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 8
File Types Character special file. A type of file providing unbuffered I/O access in variable-sized units to devices. All devices on a system are either block special files or character special files. FIFO: used for inter-process communication, named pipe (Sec. 15.5) Socket: used for network communication and can also be used for non-network communication between processes on a single host (Ch. 16) Symbolic link: points to another file (Sec. 4.16) (相當於 Windows 系統的 “ 捷徑 ” ) Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 9
Macros to detect file types Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 10 MacroType of file S_ISREG() Regular file S_ISDIR() Directory file S_ISCHR() Character special file S_ISBLK() Block special file S_ISFIFO() Pipe or FIFO S_ISLNK() Symbolic link (not in POSIX.1 or SVR4) S_ISSOCK() Socket (not in POSIX.1 or SVR4) the argument of these macros should be “stat.st_mode.”
Macros to detect IPC type Argument: struct stat POSIX.1 allows implementations to represent IPC objects as files, e.g. semaphores, message queues, etc. (No OS from the book does that now) Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 11 MacroType of object S_TYPEISMQ() Message queue S_TYPEISSEM() Semaphore S_TYPEISSHM() Shared memory object
Program 4.3: file types 1.#include “apue.h" 2. 3.int 4.main(int argc, char *argv[]) 5.{ 6. int i; 7. struct stat buf; 8. char *ptr; for (i = 1; i < argc; i++) { 11. printf("%s: ", argv[i]);printf 12. if (lstat(argv[i], &buf) < 0) { 13. err_ret("lstat error"); 14. continue; 15. } Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 12
Program 4.3: file types 1. if (S_ISREG(buf.st_mode)) ptr = "regular"; 2. else if (S_ISDIR(buf.st_mode)) ptr = "directory"; 3. else if (S_ISCHR(buf.st_mode)) ptr = "character special"; 4. else if (S_ISBLK(buf.st_mode)) ptr = "block special"; 5. else if (S_ISFIFO(buf.st_mode)) ptr = "fifo"; 6. else if (S_ISLNK(buf.st_mode)) ptr = "symbolic link"; 7. else if (S_ISSOCK(buf.st_mode)) ptr = "socket"; 8. else ptr = "** unknown mode **"; 9. printf("%s\n", ptr);printf 10. } 11. exit(0); 12.} Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 13
Program 4.3: (output) $./a.out /etc/passwd /etc /dev/initctl /dev/log /dev/tty /dev/scsi/host0/bus0/target0/lun0/cd /dev/cdrom /etc/passwd: regular /etc: directory /dev/initctl: fifo /dev/log: socket /dev/tty: character special /dev/scsi/host0/bus0/target0/lun0/cd: block special /dev/cdrom: symbolic link Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 14
Counts and percentages of different file types Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 15 File typeCountPercentage Regular file226, % Directory23, % Symbolic link6, % Character special % Block special % Socket690.03% FIFO10.0%
Set-User-ID & Set-Group-ID Each process has 6 or more IDs: Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 16 Real user ID Real group ID Who we really are Effective user ID Effective group ID Supplementary group IDs Used for file access permission checks Saved set-user-ID Saved set-group-ID Saved by exec functions
Set-User-ID & Set-Group-ID A special flag in “ st_mode ” says: “ when this file is executed, set the effective user ID of the process to be the owner of the file (st_uid) ” Example: “ passwd ” is set-user-id, user can thus write to: /etc/passwd or /etc/shadow (which are root-writable only) Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 17
File Access Permission 9 permission bits E.g.: rwxr-xr-- (read, write, execute) Divided into 3 categories User (or owner) Group Other (or world) “ chmod ” command can be used to change permission bits Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 18
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 19 File Access Permissions st_mode maskMeaning S_IRUSR user-read S_IWUSR user-write S_IXUSR user-execute S_IRGRP group-read S_IWGRP group-write S_IXGRP group-execute S_IROTH other-read S_IWOTH other-write S_IXOTH other-execute
File Access Permissions To open a file, we need execute permissions in each directory mentioned in the pathname To open /usr/include/stdio.h, need “ x ” for: / /usr /usr/include Read dir list filenames Execute dir search through (open an object in the directory) Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 20
File Access Permissions For O_TRUNC flag, we need write permission for the file To create a file, we need write and execute permissions in the directory To delete a file, we need write and execute permissions in the directory (no need of read/write permissions for the file) Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 21
File Access Permissions Kernel tests: If effective UID=0, grant access. If effective UID=owner UID: if permission bits set, grant access else deny permission If effective GID=owner GID: if permission bits set, grant access else deny permission These four steps are tried in sequence. Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 22
Ownership of New Files/Dirs New File or Directory UID = Effective UID of process GID = Effective GID of process, such as in FreeBSD and Mac OS X 10.3, OR GID of directory, such as in Linux and Solaris (with set- group-ID bit enabled) Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 23
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 24 access() 1.#include 2.int access ( const char *pathname, int mode); Returns: 0 if OK, -1 on error modeDescription R_OK Test for read permission W_OK Test for write permission X_OK Test for execute permission F_OK Test for existence of file bitwise OR
Program 4.8: access() 1.#include 2.#include “apue.h" 3. 4.int main(int argc, char *argv[]) 5.{ 6. if (argc != 2) err_quit("usage: a.out "); if (access(argv[1], R_OK) < 0) 9. err_ret("access error for %s", argv[1]); 10. else printf("read access OK\n");printf if (open(argv[1], O_RDONLY) < 0) 13. err_ret("open error for %s", argv[1]); 14. else printf("open for reading OK\n");printf exit(0); 17.} Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 25
Program 4.8: output $ ls –l a.out -rwxrwxr-x 1sar Nov 30 12:10a.out $./a.out a.out read access OK open for reading OK $ ls –l /etc/shadow -r root1315Jul /etc/shadow $./a.out /etc/shadow access error for /etc/shadow: Permission denied open error for /etc/shadow: Permission denied Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 26
Program 4.8: output (contd) $ su /* 在 ubuntu 上,用 sudo su*/ Password: # chown root a.out # chmod u+s a.out # ls –l a.out -rwsrwxr-x 1root15945Nov 30 12:10a.out # exit $./a.out /etc/shadow access error for /etc/shadow: Permission denied open for reading OK Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 27
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 28 umask() 1.#include 2.mode_t umask(mode_t cmask); Returns: previous file mode creation mask cmask = OR { S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IROTH, …} Any bits that are on in the file mode creation mask are turned off in file’s mode
Program 4.9: umask() 1.#include 2.#include “apue.h” 3.#define RWRWRW (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) 4.int main(void) { 5. umask(0); 6. if (creat("foo", RWRWRW) < 0 ) 7. err_sys("creat error for foo"); umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); 10. if (creat("bar", RWRWRW) < 0 ) 11. err_sys("creat error for bar"); 12. exit(0); 13.} Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 29
Program 4.9: output $ umask 002 (files: 666 XOR 002, dirs: 777 XOR 002) $./a.out ls –l foo bar -rw sar 0 Dec 7 21:20 bar -rw-rw-rw- 1sar 0 Dec 7 21:20 foo $ umask 002 Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 30
umask file access permission bits Single UNIX specification: Requires symbolic form $ umask 002 $ umask –S /*symbolic form*/ u=rwx, g=rwx, o=rx $ umask 027 $ umask –S u=rwx, g=rx, o= Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 31 Mask bitMeaning 0400 User-read 0200 User-write 0100 User-execute 0040 Group-read 0020 Group-write 0010 Group-execute 0004 Other-read 0002 Other-write 0001 Other-execute
chmod 1.#include 2.int chmod(const char *pathname, mode_t mode); 1.int fchmod(int filedes, mode_t mode); Return: 0 if OK, -1 on error Effective UID of process = file owner or root Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 32
mode in chmod() Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 33 modeDescription S_ISUID, S_ISGID, S_ISVTX Set UID, GID on exec saved-text (sticky bit) S_IRWXU, S_IRUSR, S_IWUSR, S_IXUSR Read, write, exec by user (owner): all or individual S_IRWXG, S_IRGRP, S_IWGRP, S_IXGRP Read, write, exec by group: all or individual S_IRWXO, S_IROTH, S_IWOTH, S_IXOTH Read, write, exec by other (world): all or individual
Program 4.12: chmod() 1.#include "apue.h" 2. 3.int main(void) { 4. struct stat statbuf; /* turn on set-group-ID and turn off group-execute */ 7. if (stat("foo", &statbuf) < 0) 8. err_sys("stat error for foo"); 9. if (chmod("foo", (statbuf.st_mode & ~S_IXGRP) | S_ISGID) < 0) 10. err_sys("chmod error for foo"); /* set absolute mode to "rw-r--r--" */ 13. if (chmod("bar", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) 14. err_sys("chmod error for bar"); 15.} Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 34
Program 4.12: output $ ls –l foo bar -rw sar 0 Dec 7 21:20 bar -rw-rw-rw 1 sar 0 Dec 7 21:20 foo After Program 4.12 execution: $ ls –l foo bar -rw-r--r-- 1 sar 0 Dec 7 21:20 bar -rw-rwSrw 1 sar 0 Dec 7 21:20 foo Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 35
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 36 chmod() The chmod functions automatically clear two of the permission bits under the following conditions: if we try to set sticky bit ( S_ISVTX ) without superuser privileges setting S_ISGID without privileges To prevent a user from creating a set-group-ID file owned by a group that the user doesn’t belong to
Sticky Bit for files Earlier versions of UNIX program’s text (machine instructions) was saved in swap space program loaded faster on 2nd execution sticky = stuck around (in swap space) saved text = sticky Newer systems have virtual memory & fast filesystem, no need of sticky bit Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 37
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 38 Sticky Bit for directories If the sticky bit is set for a directory, a file can be removed or renamed only if user has write permissions to dir and owns the file, OR owns the directory, OR is the superuser example: 1. /tmp 2. /var/spool/uucppublic The permissions for these two directories are often read, write, and execute for everyone But users should not be able to delete or rename files owned by others.
Sticky Bit for directories drwxrwxrw t 34 root wheel Mar 15 10:09 tmp/ drwxr-xr-x 18 root wheel 512 Nov usr/ drwxr-xr-x 26 root wheel 512 May var/ Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 39
chown(), fchown(), lchown() 1.#include 2.int chown(const char *pathname, uid_t owner, gid_t group); 1.int fchown(int filedes, uid_t owner, gid_t group); 1.int lchown(const char *pathname, uid_t owner, gid_t group); Return: 0 if OK, -1 on error Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 40 If either of the arguments owner or group is -1, the corresponding ID is left unchanged.
chown(), fchown(), lchown() These three functions operate similarly unless the referenced file is a symbolic link. In that case, lchown changes the owners of the symbolic link itself, not the file pointed to by the symbolic link. If _POSIX_CHOWN_RESTRICTED is in effect for the specified file, then only a superuser process can change the user ID of the file. Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 41
chown & _POSIX_CHOWN_RESTRICTED $ getconf -a | grep CHOWN _POSIX_CHOWN_RESTRICTED $ chown test examples.desktop chown: 正在更改 ‘examples.desktop’ 的擁有者 : 此項 操作並不被允許 Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 42
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 43 File Size st_size in stat structure specifies size of file in bytes st_size = 0 for an empty regular file (first read() returns EOF) st_size = multiple of 16 or 512 for directories st_size = #bytes(filename) for links lrwxrwxrwx 1 root 7 Sep 25 07:14 lib => usr/lib
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 44 Holes in a File $ ls –l core -rw-r--r-- 1 sar Nov 18 12:18 core $ du –s core 272 core ( byte blocks=139,264 bytes) Many holes in the file!
Holes in a File $ wc –c core core Normal I/O operations read through file $ cat core > core.copy $ ls –l core* -rw-r--r-- 1 stevens Nov 18 12:18 core -rw-rw-r-- 1 stevens Nov 18 12:27 core.copy $ du –s core* 272core 16592core.copy x 512 = 8,495,104 bytes Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 45
Holes in a File (Linux, ubuntu) $ du -sh core* 460Kcore.ls $ ls -l core* -rw shiwulo shiwulo 月 15 11:08 core.ls Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 46
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 47 File Truncation 1.#include 2.int truncate(const char *pathname, off_t length); 3.int ftruncate(int filedes, off_t length); Return: 0 if OK, -1 on error
File Truncation If the previous size was less than length, the effect is system dependent, but XSI-conforming systems will increase the file size. Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 48
File systems (Fig. 4.13) Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 49
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 50 Filesystems (Fig. 4.14)
File systems i-node contains all info about file: file type file ’ s access permission bits file size pointers to data blocks for file … i-node # in dir points to an i-node in the same file system Hence ln cannot link across file systems Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 51
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 52 Filesystem (Fig. 4.15) Sample cylinder group after creating the directory testdir
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 53 link() 1.#include 2.int link(const char *existingpath, const char *newpath); Return: 0 if OK, -1 on error Creation of a new directory entry and increment of link count must be ATOMIC!!!
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 54 unlink() 1.#include 2.int unlink(const char *pathname); Returns: 0 if OK, -1 on error Removes directory entry Decrements link count Link count = 0 & open count = 0 delete file
Program 4.16: unlink() 1.#include 2.#include "apue.h" 3. 4.int main(void) { 5. if (open("tempfile", O_RDWR) < 0) 6. err_sys("open error"); if (unlink("tempfile") < 0) 9. err_sys("unlink error"); printf("file unlinked\n");printf 12. sleep(15); 13. printf("done\n");printf 14.} Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 55
Program 4.16: output $ ls –l tempfile -rw-r--r-- 1 stevens Jul 31 13:42 tempfile $ df /home Filesystem kbytes used avail capacity Mounted on /dev/sd0h % /home $ a.out & 1364 file unlinked $ ls –l tempfile tempfile not found $ df /home Filesystem kbytes used avail capacity Mounted on /dev/sd0h % /home done $ df /home Filesystem kbytes used avail capacity Mounted on /dev/sd0h % /home Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 56 No change in space
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 57 unlink() This property of unlink is often used by a program to ensure that a temporary file it creates won't be left around in case the program crashes. The process creates a file using either open or creat and then immediately calls unlink. Only when the process either closes the file or terminates, which causes the kernel to close all its open files, is the file deleted.
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 58 remove() 1.#include 2.int remove(const char *pathname); Returns: 0 if OK, -1 on error For files: Identical to unlink() For directories: Identical to rmdir()
rename() 1.#include 2.int rename(const char *oldname, const char *newname); Returns: 0 if OK, -1 on error If new exists, it is first removed. Both old and new must be of the same type (that is, both must be either directories or non-directories) and must reside on the same file system. Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 59
Symbolic Links Can link across file systems Anyone can link to a directory Symbolic links are typically used to move a file or an entire directory hierarchy to another location on a system. Treatment of symbolic links by functions If function follows links, argument refers to the actual file If function does not follow links, argument refers to the link Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 60
Treatment of symbolic links by various functions Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 61 Whether or not chown follows a symbolic link depends on the implementation.
Symbolic links create loops $ mkdir foo make a new directory $ touch foo/a create a 0-length file $ ln -s../foo foo/testdir create a symbolic link $ ls -l foo total 0 -rw-r sar 0 Jan 22 00:16 a lrwxrwxrwx 1 sar 6 Jan 22 00:16 testdir ->../foo Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 62
Symbolic Links (loops) write a program using ftw() (walk fs) Result: foo foo/a foo/testdir foo/testdir/a foo/testdir/testdir foo/testdir/testdir/a foo/testdir/testdir/testdir foo/testdir/testdir/testdir/a ftw returned -1: Too many levels of symbolic links Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 63
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 64 Symbolic Link $ ln –s /no/such/file myfile /* 可以連結到不存在的 檔案 */ $ ls myfile myfile $ cat myfile /*open() follows symbolic links*/ cat: myfile: No such file or directory $ ls –l myfile lrwxrwxrwx 1 stevens 13 Dec 6 07:27 myfile -> /no/such/file
symlink() 1.#include 2.int symlink(const char *actualpath, const char *sympath); Returns: 0 if OK, -1 on error Creates a symbolic link: sympath => actualpath open() cannot open a link, so what if we want to read a link? Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 65
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 66 readlink() 1.#include 2.int readlink(const char *pathname, char *buf, int bufsize); Returns: #bytes read if OK, -1 on error Combines open, read, & close buf: name of link, not null terminated
File Times Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 67 FieldDescriptionExamplels option st_atim e last-access time of file data read-u st_mtim e last-mod time of file data writedefault st_ctim e last-change time of i-node status chmod, chown -c
Effect of various functions on the Access, Modification, and Changed-status times Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 68
utime() 1.#include 2.int utime(const char *pathname, const struct utimbuf *times); Returns: 0 if OK, -1 on error 1.struct utimbuf { 2. time_t actime; /* access time */ 3. time_t modtime; /*modification time */ 4.} Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 69
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 70 utime() Depends on times pointer NULL set a and m times to current Not Null set to the times pointer Access permissions required: current: someone who have write permission times: owner of the file, superuser
Program 4.21: utime() 1.#include 2.#include 3.#include "apue.h" 4. 5.int main(int argc, char *argv[]) { 6. int i, fd; 7. struct stat statbuf; 8. struct utimbuf timebuf; for (i = 1; i < argc; i++) { 11. /* fetch current times */ 12. if (stat(argv[i], &statbuf) < 0) { 13. err_ret("%s: stat error", argv[i]); 14. continue; 15. } Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 71
Program 4.21: utime() 1.if (fd=open(argv[i], O_RDWR | O_TRUNC) < 0) {/* truncate */ 2. err_ret("%s: open error", argv[i]); 3. continue; 4. } 5. close(fd); 6. timebuf.actime = statbuf.st_atime; 7. timebuf.modtime = statbuf.st_mtime; 8. if (utime(argv[i], &timebuf) < 0) {/* reset times */ 9. err_ret("%s: utime error", argv[i]); 10. continue; 11. } 12. } 13.} Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 72
Program 4.21: output $ ls –l changemod times -rwxrwxr-x 1 sar Dec 4 16:13 changemod -rwxrwxr-x 1 sar Dec 6 09:24 times $ ls –lu changemod times -rwxrwxr-x 1 stevens Feb 1 12:44 changemod -rwxrwxr-x 1 stevens Feb 1 12:44 times $ date Sun Feb 3 18:22:33 MST 1991 Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 73
Program 4.21: output (contd) $./a.out changemod times $ ls –l changemod times -rwxrwxr-x 1 stevens 0 Dec 4 16:13 changemod -rwxrwxr-x 1 stevens 0 Dec 6 09:24 times $ ls –lu changemod times -rwxrwxr-x 1 stevens 0 Feb 1 12:44 changemod -rwxrwxr-x 1 stevens 0 Feb 1 12:44 times $ ls –lc changemod times -rwxrwxr-x 1 stevens 0 Feb 3 18:23 changemod -rwxrwxr-x 1 stevens 0 Feb 3 18:23 times Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 74
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 75 mkdir() 1.#include 2.int mkdir(const char *pathname, mode_t mode); Returns: 0 if OK, -1 on error Creates a new, empty directory. and.. are automatically created mode are modified by file mode creation mask of the process
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 76 rmdir() 1.#include 2.int rmdir(const char *pathname); Returns: 0 if OK, -1 on error Link# = 0 & Open# = 0 space of dir freed
Reading Directories Anyone can read a dir with permissions Only kernel can write a dir (diff from create/deleting files in a dir) 1.struct dirent { /* defined in */ 2.ino_t d_ino; /* i-node # */ 3.char d_name[NAME_MAX + 1]; /* NULL-terminated filename */ 4.} Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 77
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 78 opendir(), rewinddir(), closedir() 1.#include 2.DIR *opendir(const char *pathname); 3.struct dirent *readdir(DIR *dp); 4.void rewinddir(DIR *dp); 5.int closedir(DIR *dp); 6.long telldir(DIR *dp); 7.void seekdir(DIR *dp, long loc);
opendir(), rewinddir(), closedir() The readdir() function returns a pointer to the next directory entry. The telldir() function returns the current location associated with the named directory stream. The seekdir() function sets the position of the next readdir() operation on the directory stream. The rewinddir() function resets the position of the named directory stream to the beginning of the directory. Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 79
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 80 Walking the filesystem See Figure 4.22 (pages 121~124) Gives the counts and percentages of different file types
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 81 chdir() 1.#include 2.int chdir(const char *pathname); 3.int fchdir(int filedes); Return: 0 if OK, -1 on error
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 82 Program #include "ourhdr.h" 2. 3.int 4.main(void) 5.{ 6. if (chdir("/tmp") < 0) 7. err_sys("chdir failed"); printf("chdir to /tmp succeeded\n");printf 10. exit(0); 11.}
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 83 Program 4.23: output $ pwd /usr/lib $ mycd chdir to /tmp succeeded $ pwd /usr/lib
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 84 getcwd() 1.#include 2.char *getcwd(char *buf, size_t size); Returns: buf if OK, NULL on error buf should be large enough to accommodate absolute pathnames plus a terminating null byte, or error.
Program 4.24: getcwd() 1.#include "apue.h" 2. 3.int main(void) { 4. char *ptr; 5. int size; if (chdir("/usr/spool/uucppublic") < 0) 8. err_sys("chdir failed"); ptr = path_alloc(&size); /* our own function */ 11. if (getcwd(ptr, size) == NULL) 12. err_sys("getcwd failed"); printf("cwd = %s\n", ptr);printf 15.} Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 85
Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 86 Program 4.24: output $ a.out cwd = /var/spool/uucppublic $ ls –l /usr/spool lrwxrwxrwx 1 root 12 Jan 31 07:57 /usr/spool =>../var/spool
Program 4.25: st_dev, st_rdev 1.#include "apue.h" 2. 3.int main(int argc, char *argv[]){ 4. int i; 5. struct stat buf; 6. for (i = 1; i < argc; i++) { 7. printf("%s: ", argv[i]);printf 8. if (lstat(argv[i], &buf) < 0) { 9. err_ret("lstat error"); continue; } 10. printf("dev = %d/%d",printf major(buf.st_dev), minor(buf.st_dev)); 1. if (S_ISCHR(buf.st_mode) || S_ISBLK(buf.st_mode)) { 2. printf(" (%s) rdev = %d/%d",printf 3. (S_ISCHR(buf.st_mode)) ? "character" : "block", 4. major(buf.st_rdev), minor(buf.st_rdev)); } 5. printf("\n");printf 6. } 7.} Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 87
Program 4.25: output $./a.out / /home/sar /dev/tty[01] /: dev = 3/3 /home/sar: dev = 3/4 /dev/tty0: dev = 0/7 (character) rdev=4/0 /dev/tty1: dev=0/7 (character) rdev=4/1 $ mount /dev/hda3 on / type ext2 (rw,noatime) /dev/hda4 on /home type ext2 (rw,noatime) $ ls –lL /dev/tty[01] /dev/hda[34] brw root 3, 3 Jan 31 08:23 /dev/hda3 brw root 3, 4 Jan 31 08:23 /dev/hda4 crw root 4, 0 Jan 31 08:22 /dev/tty0 crw root 4, 1 Jul 9 10:11 /dev/tty1 Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 88
熟悉指令與函數的關係 chown umask chmod ln (link) ln –s (symlink) ls –lc OR ls -la mkdir rmdir cd (chdir()) /dev rm (unlink) mv Slides©2006 Pao-Ann Hsiung, National Chung Cheng University, Taiwan 89