- 论坛徽章:
- 0
|
Functions associate system call
参考网站: http://linux.die.net
open, close, read, write, ftruncate, lseek, fsync, fstat, fchmod, fchown, fcntl, flock, dup, dup2, select
open and creat都能够打开文件
函数原型
#include fcntl.h>
int open(const char *pathname, int flags)
成功后返回一个文件描述符,失败后返回-1
The flags of the open( ) system call
Flag name Description
O_RDONLY Open for reading
O_WRONLY Open for writing
O_RDWR Open for both reading and writing
O_CREAT Create the file if it does not exist
O_EXCL With O_CREAT, fail if the file already exists
O_NOCTTY Never consider the file as a controlling terminal
O_TRUNC Truncate the file (remove all existing contents)
O_APPEND Always write at end of the file
O_NONBLOCK No system calls will block on the file
O_NDELAY Same as O_NONBLOCK
O_SYNC Synchronous write (block until physical write terminates)
FASYNC I/O event notification via signals
O_DIRECT Direct I/O transfer (no kernel buffering)
O_LARGEFILE Large file (size greater than 2 GB)
O_DIRECTORY Fail if file is not a directory
O_NOFOLLOW Do not follow a trailing symbolic link in pathname
O_NOATIME Do not update the inode's last access time
为了在使用完某个文件后关闭他,可以采用系统调用close.close只有一个参数,即open返回的文件描述符。close的原型:
#include
int close(int fd)
*******example************
#include //open()
#include
#include //close()
int main()
{
int fd;
char path[]="hello";
if(fd=creat(path, O_CREAT|O_TRUNC|O_WRONLY, 0644)
ssize_t read(int fd, const void *buf, size_t count)
ssize_t write(int fd, const void *buf, size_t count)
fd 是以前的open调用返回的有效文件描述符。buf是保存缓冲区的指针,而count指定写入的字节数
READ()
Description
read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.
If count is zero, read() returns zero and has no other results. If count is greater than SSIZE_MAX, the result is unspecified.
Return Value
On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. On error, -1 is returned, and errno is set appropriately. In this case it is left unspecified whether the file position (if any) changes.
write()
Description
write() writes up to count bytes to the file referenced by the file descriptor fd from the buffer starting at buf. POSIX requires that a read() which can be proved to occur after a write() has returned returns the new data. Note that not all file systems are POSIX conforming.
Return Value
On success, the number of bytes written are returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately. If count is zero and the file descriptor refers to a regular file, 0 may be returned, or an error could be detected. For a special file, the results are not portable.
ftruncate缩短文件
系统调用把ftruncate把文件描述符fd引用的文件缩短到length指定的长度
#include
int ftruncate(int fd, off_t length)
lseek定位文件指针
函数lseek在用描述符fd打开的文件里把文件指针设定到相对于whence值偏移的位置,文件指针是文件中执行操作的位置
#include
#include
off_t lseek(int fd, off_t offset, int whence);
Description
The lseek() function repositions the offset of the open file associated with the file descriptor fildes to the argument offset according to the directive whence as follows:
SEEK_SET
The offset is set to offset bytes. 从文件的开始处计算
SEEK_CUR
The offset is set to its current location plus offset bytes.
SEEK_END
The offset is set to the size of the file plus offset bytes.
The lseek() function allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a "hole") return null bytes ('\0') until data is actually written into the gap.
Return Value
Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file. Otherwise, a value of (off_t)-1 is returned and errno is set to indicate the error.
Fsync(同步到硬盘)
fsync, fdatasync - synchronize(同步) a file's in-core state with storage device(存储设备,如硬盘)
Synopsis
#include unistd.h>
int fsync(int fd);
int fdatasync(int fd);
Description
fsync() transfers ("flushes") all modified in-core data of (i.e., modified buffer cache pages for) the file referred to by the file descriptor fd to the disk device (or other permanent storage device) where that file resides. The call blocks until the device reports that the transfer has completed. It also flushes metadata information associated with the file (see stat(2)).
Calling fsync() does not necessarily ensure that the entry in the directory containing the file has also reached disk. For that an explicit fsync() on a file descriptor for the directory is also needed.
fdatasync() is similar to fsync(), but does not flush modified metadata unless that metadata is needed in order to allow a subsequent data retrieval to be correctly handled. For example, changes to st_atime or st_mtime (respectively, time of last access and time of last modification; see stat(2)) do not not require flushing because they are not necessary for a subsequent data read to be handled correctly. On the other hand, a change to the file size (st_size, as made by say ftruncate(2)), would require a metadata flush.
The aim of fdatasync(2) is to reduce disk activity for applications that do not require all metadata to be synchronised with the disk.
Return Value
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
Name
stat, fstat, lstat - get file status
Synopsis
#include sys/types.h>
#include sys/stat.h>
#include unistd.h>
int stat(const char *path, struct stat *buf);
int fstat(int filedes, struct stat *buf);
int lstat(const char *path, struct stat *buf);
Description
These functions return information about a file. No permissions are required on the file itself, but -- in the case of stat() and lstat() -- execute (search) permission is required on all of the directories in path that lead to the file.
stat() stats the file pointed to by path and fills in buf.
lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor filedes.
All of these system calls return a stat structure, which contains the following fields:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for filesystem I/O */
blkcnt_t st_blocks; /* number of blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};
The st_dev field describes the device on which this file resides.
The st_rdev field describes the device that this file (inode) represents.
The st_size field gives the size of the file (if it is a regular file or a symbolic link) in bytes. The size of a symlink is the length of the pathname it contains, without a trailing null byte.
The st_blocks field indicates the number of blocks allocated to the file, 512-byte units. (This may be smaller than st_size/512, for example, when the file has holes.)
The st_blksize field gives the "preferred" blocksize for efficient file system I/O. (Writing to a file in smaller chunks may cause an inefficient read-modify-rewrite.)
Not all of the Linux filesystems implement all of the time fields. Some file system types allow mounting in such a way that file accesses do not cause an update of the st_atime field. (See 'noatime' in mount(8).)
The field st_atime is changed by file accesses, e.g. by execve(2), mknod(2), pipe(2), utime(2) and read(2) (of more than zero bytes). Other routines, like mmap(2), may or may not update st_atime.
The field st_mtime is changed by file modifications, e.g. by mknod(2), truncate(2), utime(2) and write(2) (of more than zero bytes). Moreover, st_mtime of a directory is changed by the creation or deletion of files in that directory. The st_mtime field is not changed for changes in owner, group, hard link count, or mode.
The field st_ctime is changed by writing or by setting inode information (i.e., owner, group, link count, mode, etc.).
The following POSIX macros are defined to check the file type using the st_mode field:
S_ISREG(m)
is it a regular file?
S_ISDIR(m)
directory?
S_ISCHR(m)
character device?
S_ISBLK(m)
block device?
S_ISFIFO(m)
FIFO (named pipe)?
S_ISLNK(m)
symbolic link? (Not in POSIX.1-1996.)
S_ISSOCK(m)
socket? (Not in POSIX.1-1996.)
The following flags are defined for the st_mode field:
S_IFMT 0170000 bitmask for the file type bitfields
S_IFSOCK 0140000 socket
S_IFLNK 0120000 symbolic link
S_IFREG 0100000 regular file
S_IFBLK 0060000 block device
S_IFDIR 0040000 directory
S_IFCHR 0020000 character device
S_IFIFO 0010000 FIFO
S_ISUID 0004000 set UID bit
S_ISGID 0002000 set-group-ID bit (see below)
S_ISVTX 0001000 sticky bit (see below)
S_IRWXU 00700 mask for file owner permissions
S_IRUSR 00400 owner has read permission
S_IWUSR 00200 owner has write permission
S_IXUSR 00100 owner has execute permission
S_IRWXG 00070 mask for group permissions
S_IRGRP 00040 group has read permission
S_IWGRP 00020 group has write permission
S_IXGRP 00010 group has execute permission
S_IRWXO 00007 mask for permissions for others (not in group)
S_IROTH 00004 others have read permission
S_IWOTH 00002 others have write permission
S_IXOTH 00001 others have execute permission
The set-group-ID bit (S_ISGID) has several special uses. For a directory it indicates that BSD semantics is to be used for that directory: files created there inherit their group ID from the directory, not from the effective group ID of the creating process, and directories created there will also get the S_ISGID bit set. For a file that does not have the group execution bit (S_IXGRP) set, the set-group-ID bit indicates mandatory file/record locking.
The 'sticky' bit (S_ISVTX) on a directory means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of the directory, and by a privileged process.
Linux Notes
Since kernel 2.5.48, the stat structure supports nanosecond resolution for the three file timestamp fields. Glibc exposes the nanosecond component of each field using names either of the form st_atim.tv_nsec, if the _BSD_SOURCE or _SVID_SOURCE feature test macro is defined, or of the form st_atimensec, if neither of these macros is defined. On file systems that do not support sub-second timestamps, these nanosecond fields are returned with the value 0.
For most files under the /proc directory, stat() does not return the file size in the st_size field; instead the field is returned with the value 0.
Return Value
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
fchown改变文件的所有权
chown, fchown, lchown - change ownership of a file
Synopsis
#include sys/types.h>
#include unistd.h>
int chown(const char *path, uid_t owner, gid_t group);
int fchown(int fd, uid_t owner, gid_t group);
int lchown(const char *path, uid_t owner, gid_t group);
Description
These system calls change the owner and group of the file specified by path or by fd. Only a privileged process (Linux: one with the CAP_CHOWN capability) may change the owner of a file. The owner of a file may change the group of the file to any group of which that owner is a member. A privileged process (Linux: with CAP_CHOWN) may change the group arbitrarily.
If the owner or group is specified as -1, then that ID is not changed.
When the owner or group of an executable file are changed by a non-superuser, the S_ISUID and S_ISGID mode bits are cleared. POSIX does not specify whether this also should happen when root does the chown(); the Linux behaviour depends on the kernel version. In case of a non-group-executable file (with clear S_IXGRP bit) the S_ISGID bit indicates mandatory locking, and is not cleared by a chown().
Return Value
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
fchmod改变文件读写权
Name
chmod, fchmod - change permissions of a file
Synopsis
#include sys/types.h>
#include sys/stat.h>
int chmod(const char *path, mode_t mode);
int fchmod(int fd, mode_t mode);
Description
The mode of the file given by path or referenced by fd is changed.
Modes are specified by or'ing the following:
S_ISUID
04000 set user ID on execution
S_ISGID
02000 set group ID on execution
S_ISVTX
01000 sticky bit
S_IRUSR
00400 read by owner
S_IWUSR
00200 write by owner
S_IXUSR
00100 execute/search by owner
S_IRGRP
00040 read by group
S_IWGRP
00020 write by group
S_IXGRP
00010 execute/search by group
S_IROTH
00004 read by others
S_IWOTH
00002 write by others
S_IXOTH
00001 execute/search by others
The effective UID of the calling process must match the owner of the file, or the process must be privileged (Linux: it must have the CAP_FOWNER capability).
If the calling process is not privileged (Linux: does not have the CAP_FSETID capability), and the group of the file does not match the effective group ID of the process or one of its supplementary group IDs, the S_ISGID bit will be turned off, but this will not cause an error to be returned.
As a security measure, depending on the file system, the set-user-ID and set-group-ID execution bits may be turned off if a file is written. (On Linux this occurs if the writing process does not have the CAP_FSETID capability.) On some file systems, only the superuser can set the sticky bit, which may have a special meaning. For the sticky bit, and for set-user-ID and set-group-ID bits on directories, see stat(2).
On NFS file systems, restricting the permissions will immediately influence already open files, because the access control is done on the server, but open files are maintained by the client. Widening the permissions may be delayed for other clients if attribute caching is enabled on them.
Return Value
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
flock and fcntl给文件加锁
Name
flock - apply or remove an advisory lock on an open file
Synopsis
#include
int flock(int fd, int operation);
Description
Apply or remove an advisory lock on the open file specified by fd. The parameter operation is one of the following:
LOCK_SH
Place a shared lock. More than one process may hold a shared lock for a given file at a given time.
LOCK_EX
Place an exclusive lock. Only one process may hold an exclusive lock for a given file at a given time.
LOCK_UN
Remove an existing lock held by this process.
A call to flock() may block if an incompatible lock is held by another process. To make a non-blocking request, include LOCK_NB (by ORing) with any of the above operations.
A single file may not simultaneously have both shared and exclusive locks.
Locks created by flock() are associated with an open file table entry. This means that duplicate file descriptors (created by, for example, fork(2) or dup(2)) refer to the same lock, and this lock may be modified or released using any of these descriptors. Furthermore, the lock is released either by an explicit LOCK_UN operation on any of these duplicate descriptors, or when all such descriptors have been closed.
If a process uses open(2) (or similar) to obtain more than one descriptor for the same file, these descriptors are treated independently by flock(). An attempt to lock the file using one of these file descriptors may be denied by a lock that the calling process has already placed via another descriptor.
A process may only hold one type of lock (shared or exclusive) on a file. Subsequent flock() calls on an already locked file will convert an existing lock to the new lock mode.
Locks created by flock() are preserved across an execve(2).
A shared or exclusive lock can be placed on a file regardless of the mode in which the file was opened.
Return Value
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
dup and dup2
dup, dup2 - duplicate a file descriptor
Synopsis
#include
int dup(int oldfd);int dup2(int oldfd, int newfd);
Description
dup() and dup2() create a copy of the file descriptor oldfd.
After a successful return from dup() or dup2(), the old and new file descriptors may be used interchangeably. They refer to the same open file description (see open(2)) and thus share file offset and file status flags; for example, if the file offset is modified by using lseek(2) on one of the descriptors, the offset is also changed for the other.
The two descriptors do not share file descriptor flags (the close-on-exec flag). The close-on-exec flag (FD_CLOEXEC; see fcntl(2)) for the duplicate descriptor is off.
dup() uses the lowest-numbered unused descriptor for the new descriptor.
dup2() makes newfd be the copy of oldfd, closing newfd first if necessary.
Return Value
dup() and dup2() return the new descriptor, or -1 if an error occurred (in which case, errno is set appropriately).
使用select同时读写多个文件
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/45689/showart_683451.html |
|