APUE Reading Notes------Chapter 4

来源:互联网 发布:nginx日志名字 编辑:程序博客网 时间:2024/05/29 12:32

Chapter4. Files and Directories

    4.2 stat, fstat, and lstat Functions

    #include <sys/stat.h>

   

    int stat(const char *restrict pathname,struct stat *restrict buf);

    int fstat(int filedes, struct stat *buf);

    int lstat(const char *restrict pathname,struct stat *restrict buf);

    Returns: All three return: 0 if OK, -1 onerror.

 

    Given a pathname, the stat function returnsa structure of information about the named file. The fstat function obtainsinformation about the file that is already open on the descriptor filedes. Thelstat function is similar to stat, but when the named file is a symbolic link,lstat returns information about the symbolic link, not the file referenced bythe symbolic link.

 

    The second argument is a pointer to astructure that we must supply. The function fills in the structure pointed toby buf.

    The biggest user of the stat functions isprobably the ls –l command, to learn all the information about a file.

    4.3 File Types

    Most files on a UNIX system are eitherregular files or directories, but there are additional types of files. Thetypes are:

1.  Regular file. S_ISREG()

2.  Directory file. S_ISDIR()

3.  Block special file. S_ISBLK()

4.  Character special file. S_ISCHR()

5.  FIFO. S_ISFIFO()

6.  Socket. S_ISSOCK()

7.  Symbolic link. S_ISLNK()

The type of a file is encoded in the st_modemember of the stat structure.

 

4.4 Set-User-ID and Set-Group-ID

 

User IDs and group IDs associated with eachprocess

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

 

Every file has an owner and a group owner.The owner is specified by the st_uid member of the stat structure; the groupowner, by the st_gid member.

 

4.5 File Access Permissions

    Thest_mode value also encodes the access permission bits for the file.

    Thenine file access permission bits, from <sys/stat.h>

    st_modemask      Meaning

    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

 

The first rule is that whenever we want toopen any type of file by name, we must have execute permission in eachdirectory mentioned in the name, including the current directory, if it isimplied. This is why the execute permission bit for a directory is often calledthe search bit.

 

We cannot create a new file in a directoryunless we have write permission and execute permission in the directory.

 

To delete an existing file, we need writepermission and execute permission in the directory containing the file. We donot need read permission for the file itself.

 

The file access tests performed by the kernelare as follows:

1.  If the effective user ID of theprocess is 0, access is allowed.

2.  If the effective user ID of theprocess equals the owner ID of the file, access is allowed if the appropriateuser access permission bit is set. Otherwise, permission is denied.

3.  If the effective group ID of theprocess or one of the supplementary group IDs of the process equals the groupID of the file, access is allowed if the appropriate group access permissionbit is set. Otherwise, permission is denied.

4.  If the appropriate other accesspermission bit is set, access is allowed. Otherwise, permission is denied.

These four steps are tried in sequence.

 

4.6 Ownership of New Files and Directories

The user ID of a new file is set to theeffective user ID of the process. POSIX.1 allows an implementation to chooseone of the following options to determine the group ID of a new file./

1.  The group ID of a new file can bethe effective group ID of the process.

2.  The group ID of a new file can bethe group ID of the directory in which the file is being created.

 

4.7 access Function

 

The access function bases its tests on thereal user and group IDs.

#include <unistd.h>

int access(const char *pathname, int mode);

Returns: 0 if OK, -1 on error.

 

The mode:

 

mode             Description

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

 

4.8 umask Function

The umask function sets the file modecreation mask for the process and returns the previous value.

#include <sys/stat.h>

 

mode_t umask(mode_t cmask);

Returns: previous file mode creation mask

The cmask argument is formed as the bitwiseOR of the nine constant from: S_IRUSR, S_IWUSR, and so on.

 

The file node creation mask is used wheneverthe process creates a new file or a new directory. We describe how to create anew directory. Any bits that are on in the file mode creation mask are turnedoff in the file’s mode.

 

4.9 chmod and fchmod Functions

These two functions allow us to change thefile access permission for an existing file.

#include <sys/stat.h>

 

int chmod(const char *pathname, mode_t mode);

int fchmod(int filedes, mode_t mode);

Both return: o if OK, -1 on error.

 

The chmod function operates on the specifiedfile, whereas the fchmod function operates on a file that has already beenopened.

 

To change the permission bits of a file, theeffective user ID of the process must be equal to the owner ID of the file, orthe process must have superuser permission.

 

4.10 Sticky Bit

On contemporary systems, the use of thesticky bit has been extended. The Single UNIX Specification allows the stickybit to be set for a directory. If the bit is set for a directory, a file in thedirectory can be removed or renamed only if the user has write permission forthe directory and one of the following:

Owns the file

Owns the directory

Is the superuser

 

4.11 chown, fchown, and lchown Functions

The chown functions allow us to change theuser ID of a file and the group ID of a file.

#include <unistd.h>

 

int chown(const char *pathname, uis_t owner,gid_t group);

int fchown(int filedes, uid_t owner, gid_tgroup);

int lchown(const char *pathname, uid_t owner,gid_t group);

All three return: 0 if OK, - 1on error.

 

These three functions operate similarlyunless the referenced file is a symbolic link. In that case, lchown changes theowners of the symbolic link itself, not the file pointed to by the symboliclink.

 

If either of the arguments owner or group is-1, the corresponding ID is left unchanged.

 

When _POSIX_CHOWN_RESTRICTED is in effect,you can’t change the user ID of other users’ files. You can change the group IDof files that you own, but only to groups that you belong to.

 

4.12 File Size

The st_size member of the stat structurecontains the size of the file in bytes. This is meaningful only for regularfiles, directories, and symbolic links.

 

Holes in a File

Holes are created by seeking past the currentend of file and writing some data.

 

4.13 File Truncation

#include <unistd.h>

 

int truncate(const char *pathname, off_tlength);

int ftruncate(int filedes, off_t length);

Both return: 0 if OK, -1 on error.

 

These two functions truncate an existing fileto length bytes.

If the previous size was led than length, theeffect is system dependent.

 

4.14 File Systems

Disk drive, partitions, and a file system


The i-nodes are fixed-length entries thatcontain most of the information about a file.

 

 //img

Cylinder group’s i-nodes and data blocks inmore detail

 //img

More Info: http://blog.csdn.net/wanpengcoder/archive/2010/12/08/6063076.aspx

 

4.15 link, unlink, remove, and renameFunctions

The way we create a link to an existing fileis with the link function.

#include <unistd.h>

 

int link(const char *existingpath, const char*newpath);

Returns: 0 if OK, -1 on error.

 

The creation of the new directory entry andthe increment of the link count must be atomic operation.

 

To remove an existing directory entry, wecall the unlink function.

#include <unistd.h>

 

int unlink(const char *pathname);

Returns: 0 if OK, -1 on error.

 

We’ve mentioned before that to unlink a file,we must have write permission and execute permission in the directorycontaining the directory entry, as it is the directory entry that we will beremoving. If the sticky bit is set in this directory we must have writepermission for the directory and one of the following:

Own the file.

Own the directory.

Have superuser privileges.

 

Only when the link count reaches 0 can thecontents of file be deleted.

 

The process creates a file using either openor creat and then immediately calls unlink. The file is not deleted, however,because it is still open.

 

If pathname is a symbolic link, unlinkremoves the symbolic link, not the file referenced by the link. There is nofunction to remove the file referenced by a symbolic link given the name of thelink.

 

We can also unlink a file or a directory withthe remove function. For a file, remove is identical to unlink. For adirectory, remove is identical to rmdir.

#include <stdio.h>

 

int remove(const char *pathname);

Returns: 0 if OK, -1 on error.

 

A file or a directory id renamed with therename function.

#include <stdio.h>

 

int rename(const char *oldname, const char*newname);

Returns: 0 if OK, -1 on error.

 

If newname already exists, we need permissionsas if we were deleting it. Also, because we’re removing the directory entry foroldname and possibly creating a directory entry for newname, we need writepermission and execute permission in the directory containing oldname and inthe directory containing newname.

 

4.16 Symbolic Links

Symbolic links were introduced to get aroundthe limitations of hard links.

Hard links normally require that the link andthe file reside in the same file system

Only the superuser can create a hard link toa directory.

 

There are no file system limitations on a symboliclink and what it points to, and anyone can create a symbolic link to adirectory.

//img

 

4.17 symlink and readlink Functions

A symbolic link is created with the symlinkfunction.

 

#include <unistd.h>

 

int symlink(const char *actualpath, constchar *sympath);

Returns: 0 if OK, -1 on error.

 

Because the open function follows a symboliclink, we need a way to open the link itself and read the name in the link. Thereadlink function does this.

#include <unistd.h>

 

ssize_t readlink(const char *restrict pathname,char *restrict buf, size_t bufsize);

Returns: number of bytes read if OK, -1 onerror.

 

4.18 File Times

//img

Note the different between the modificationtime and the changed-status time. The modification time is when the contents ofthe file were last modified. The changed-status time is when the i-node of thefile was last modified.

 

    4.19 utime Function

    The access time and the modification time ofa file can be changed with the utime function.

    #include <utime.h>

   

    int utime(const char *pathname, const structutimbuf *times);

    Returns: 0 if OK, -1 on error.

    struct utimbuf{

    time_tactime;

    time_tmodtime;

};

 

The operation of this function, and theprivileges required to execute it, depend on whether the times argument isNULL.

If times is a null pointer, the access timeand modification time are both set to the current time.

If times is a non-null pointer, the accesstime and the modification time are set to the values in the structure pointedto by times.

Note that we are unable to specify a valuefor the changed-status time, st_ctime the time the i-node was last changed asthis field automatically updated when the utime function is called.

 

4.20 mkdir and rmdir Functions

Directories are created with the mkdirfunction and deleted with the rmdir function.

#include <sys/stat.h>

 

int mkdir(const char *pathname, mode_t mode);

Returns: 0 if OK, -1 on error.

 

A common mistake is to specify the same modeas for a file: read and write permissions only. But for a directory, wenormally want at least one of the execute bits enabled, to allow access tofilenames within the directory.

 

An empty directory is deleted with the rmdirfunction.

#include <unistd.h>

 

int rmdir(const char *pathnem);

Returns: 0 if OK, -1 on error.

 

4.21 Reading Directories

Directoried can be read by anyone who hasaccess permission to read the directory. But only the kernel can write to adirectory, to preserve file system sanity.

 

#include <dirent.h>

 

DIR *opendir(const char *pathname);

Returns: pointer if OK, NULL on error.

 

struct dirent *readdir(DIR *dp);

Returns: pointer if OK, NULL at end ofdirectory or error.

 

void rewinddir(DIR *dp);

int closedir(DIR *dp);

Returns: 0 if OK, -1 on error.

 

long telldir(DIR *dp);

Returns: current location in directoryassociated with dp

 

void seekdir(DIR *dp, long loc);

 

 

dirent structure:

 

struct dirent{

    ino_td_ino; /* i-node number */

    chard_name[NAME_MAX + 1]; /* null-terminated filename */

};

 

The pointer to a DIR structure that isreturned by opendir is then used with the other five functions. The opendirfunction initializes things so that the first readdir reads the first entry inthe directory. The ordering of entries within the directory is implementationdependent and is usually not alphabetical.

 

4.22 chdir, fchdir, and getcwd Functions

The current working directory is an attributeof a process; the home directory is an attribute of a login name.

 

We can change the current working directoryof the calling process by calling the chdir or fchdir functions.

#include <unistd.h>

 

int chdir(const char *pathname);

int fchdir(int filedes);

Both return: 0 if OK, -1 on error.

 

Get absolute pathname of the current workingdirectory.

#include <unistd.h>

 

char *getcwd(char *buf, size_t size);

Returns: buf if OK, NULL on error.

 

4.23 Device Special Files

Every file system is known by its major andminor device numbers, which are encoded in the primitive system data typedev_t.

 

We can usually access the major and minordevice numbers through two macros defined by most implementations: major andminor.

 

The st_dev value for every filename on asystem is the device number of the file system containing that filename and itscorresponding i-node.

Only character special files and blockspecial files have an st_rdev value.

 

4.24 Summary of File Access Permission Bits

//img

原创粉丝点击