赞
踩
UNIX 文件I/O系统调用),主要包括:
int open(const char *path, int oflag, ...); #include <sys/stat.h> #include <fcntl.h> oflag的用法: {O_RDONLY|O_RDWR|O_WRONLY} | [O_APPEND,O_CLOEXEC,O_CREAT,O_DIRECTORY,... O_DSYNC,O_EXCL,O_NOCTTY,O_NOFOLLOW,O_NONBLOCK,O_RSYNC,O_SYNC,O_TRUNC] O_EXEC Open for execute only (non-directory files). The result is unspecified if this flag is applied to a directory. O_RDONLY Open for reading only. O_RDWR Open for reading and writing. The result is undefined if this flag is applied to a FIFO. O_SEARCH Open directory for search only. The result is unspecified if this flag is applied to a non-directory file. O_WRONLY Open for writing only. Any combination of the following may be used: O_APPEND If set, the file offset shall be set to the end of the file prior to each write. O_CLOEXEC If set, the FD_CLOEXEC flag for the new file descriptor shall be set. O_CREAT If the file exists, this flag has no effect except as noted under O_EXCL below. Otherwise, the file shall be created; the user ID of the file shall be set to the effective user ID of the process; the group ID of the file shall be set to the group ID of the file's parent directory or to the effective group ID of the process; and the access permission bits (see <sys/stat.h>) of the file mode shall be set to the value of the argument fol‐ lowing the oflag argument taken as type mode_t modified as follows: a bitwise AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask. Thus, all bits in the file mode whose corresponding bit in the file mode cre‐ ation mask is set are cleared. When bits other than the file permission bits are set, the effect is unspecified. The argument following the oflag argument does not affect whether the file is open for reading, writing, or for both. Implementations shall provide a way to initialize the file's group ID to the group ID of the parent direc‐ tory. Implementations may, but need not, provide an implementation-defined way to initialize the file's group ID to the effective group ID of the calling process. If the file does not exist, it will be created. The owner (user ID) of the file is set to the effective user ID of the process. The group ownership (group ID) is set either to the effective group ID of the process or to the group ID of the parent direc‐ tory (depending on filesystem type and mount options, and the mode of the parent directory; see the mount options bsdgroups and sysvgroups described in mount(8)). mode specifies the mode to use in case a new file is created. This argument must be supplied when O_CREAT or O_TMPFILE is specified in flags; if neither O_CREAT nor O_TMPFILE is speci‐ fied, then mode is ignored. The effective mode is modified by the process's umask in the usual way: in the absence of a default ACL, the mode of the created file is (mode & ~umask). Note that this mode applies only to future accesses of the newly created file; the open() call that creates a read-only file may well return a read/write file descriptor. The following symbolic constants are provided for mode: S_IRWXU 00700 user (file owner) has read, write, and execute permission S_IRUSR 00400 user has read permission S_IWUSR 00200 user has write permission S_IXUSR 00100 user has execute permission S_IRWXG 00070 group has read, write, and execute permission S_IRGRP 00040 group has read permission S_IWGRP 00020 group has write permission S_IXGRP 00010 group has execute permission S_IRWXO 00007 others have read, write, and execute permission S_IROTH 00004 others have read permission S_IWOTH 00002 others have write permission S_IXOTH 00001 others have execute permission According to POSIX, the effect when other bits are set in mode is unspecified. On Linux, the following bits are also honored in mode: S_ISUID 0004000 set-user-ID bit S_ISGID 0002000 set-group-ID bit (see stat(2)) S_ISVTX 0001000 sticky bit (see stat(2)) O_DIRECTORY If path resolves to a non-directory file, fail and set errno to [ENOTDIR]. O_DSYNC Write I/O operations on the file descriptor shall com‐ plete as defined by synchronized I/O data integrity com‐ pletion. O_EXCL If O_CREAT and O_EXCL are set, open() shall fail if the file exists. The check for the existence of the file and the creation of the file if it does not exist shall be atomic with respect to other threads executing open() naming the same filename in the same directory with O_EXCL and O_CREAT set. If O_EXCL and O_CREAT are set, and path names a symbolic link, open() shall fail and set errno to [EEXIST], regardless of the contents of the sym‐ bolic link. If O_EXCL is set and O_CREAT is not set, the result is undefined. O_NOCTTY If set and path identifies a terminal device, open() shall not cause the terminal device to become the con‐ trolling terminal for the process. If path does not iden‐ tify a terminal device, O_NOCTTY shall be ignored. O_NOFOLLOW If path names a symbolic link, fail and set errno to [ELOOP]. O_NONBLOCK When opening a FIFO with O_RDONLY or O_WRONLY set: * If O_NONBLOCK is set, an open() for reading-only shall return without delay. An open() for writing- only shall return an error if no process currently has the file open for reading. * If O_NONBLOCK is clear, an open() for reading-only shall block the calling thread until a thread opens the file for writing. An open() for writing-only shall block the calling thread until a thread opens the file for reading. When opening a block special or character special file that supports non-blocking opens: * If O_NONBLOCK is set, the open() function shall return without blocking for the device to be ready or available. Subsequent behavior of the device is device-specific. * If O_NONBLOCK is clear, the open() function shall block the calling thread until the device is ready or available before returning. Otherwise, the O_NONBLOCK flag shall not cause an error, but it is unspecified whether the file status flags will include the O_NONBLOCK flag. O_RSYNC Read I/O operations on the file descriptor shall complete at the same level of integrity as specified by the O_DSYNC and O_SYNC flags. If both O_DSYNC and O_RSYNC are set in oflag, all I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion. If both O_SYNC and O_RSYNC are set in flags, all I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion. O_SYNC Write I/O operations on the file descriptor shall com‐ plete as defined by synchronized I/O file integrity com‐ pletion. The O_SYNC flag shall be supported for regular files, even if the Synchronized Input and Output option is not supported. O_TRUNC If the file exists and is a regular file, and the file is successfully opened O_RDWR or O_WRONLY, its length shall be truncated to 0, and the mode and owner shall be unchanged. It shall have no effect on FIFO special files or terminal device files. Its effect on other file types is implementation-defined. The result of using O_TRUNC without either O_RDWR or O_WRONLY is undefined. O_TTY_INIT If path identifies a terminal device other than a pseudo- terminal, the device is not already open in any process, and either O_TTY_INIT is set in oflag or O_TTY_INIT has the value zero, open() shall set any non-standard termios structure terminal parameters to a state that provides conforming behavior; see the Base Definitions volume of POSIX.1‐2008, Section 11.2, Parameters that Can be Set. It is unspecified whether O_TTY_INIT has any effect if the device is already open in any process. If path iden‐ tifies the slave side of a pseudo-terminal that is not already open in any process, open() shall set any non- standard termios structure terminal parameters to a state that provides conforming behavior, regardless of whether O_TTY_INIT is set. If path does not identify a terminal device, O_TTY_INIT shall be ignored.
NAME creat — create a new file or rewrite an existing one SYNOPSIS #include <sys/stat.h> #include <fcntl.h> int creat(const char *path, mode_t mode); DESCRIPTION The creat() function shall behave as if it is implemented as follows: int creat(const char *path, mode_t mode) { return open(path, O_WRONLY|O_CREAT|O_TRUNC, mode); } If the file does not exist, it will be created. The owner (user ID) of the file is set to the effective user ID of the process. The group ownership (group ID) is set either to the effective group ID of the process or to the group ID of the parent direc‐ tory (depending on filesystem type and mount options, and the mode of the parent directory; see the mount options bsdgroups and sysvgroups described in mount(8)). mode specifies the mode to use in case a new file is created. This argument must be supplied when O_CREAT or O_TMPFILE is specified in flags; if neither O_CREAT nor O_TMPFILE is speci‐ fied, then mode is ignored. The effective mode is modified by the process's umask in the usual way: in the absence of a default ACL, the mode of the created file is (mode & ~umask). Note that this mode applies only to future accesses of the newly created file; the open() call that creates a read-only file may well return a read/write file descriptor. The following symbolic constants are provided for mode: S_IRWXU 00700 user (file owner) has read, write, and execute permission S_IRUSR 00400 user has read permission S_IWUSR 00200 user has write permission S_IXUSR 00100 user has execute permission S_IRWXG 00070 group has read, write, and execute permission S_IRGRP 00040 group has read permission S_IWGRP 00020 group has write permission S_IXGRP 00010 group has execute permission S_IRWXO 00007 others have read, write, and execute permission S_IROTH 00004 others have read permission S_IWOTH 00002 others have write permission S_IXOTH 00001 others have execute permission According to POSIX, the effect when other bits are set in mode is unspecified. On Linux, the following bits are also honored in mode: S_ISUID 0004000 set-user-ID bit S_ISGID 0002000 set-group-ID bit (see stat(2)) S_ISVTX 0001000 sticky bit (see stat(2))
NAME
close — close a file descriptor
SYNOPSIS
#include <unistd.h>
int close(int fildes);
NAME lseek — move the read/write file offset SYNOPSIS #include <unistd.h> off_t lseek(int fildes, off_t offset, int whence); DESCRIPTION The lseek() function shall set the file offset for the open file description associated with the file descriptor fildes, as follows: * If whence is SEEK_SET, the file offset shall be set to offset bytes. * If whence is SEEK_CUR, the file offset shall be set to its current location plus offset. * If whence is SEEK_END, the file offset shall be set to the size of the file plus offset. The symbolic constants SEEK_SET, SEEK_CUR, and SEEK_END are defined in <unistd.h>. The behavior of lseek() on devices which are incapable of seeking is implementation-defined. The value of the file offset associated with such a device is undefined. The lseek() function shall allow the file offset to be set beyond the end of the existing data in the file. If data is later written at this point, subsequent reads of data in the gap shall return bytes with the value 0 until data is actually written into the gap. The lseek() function shall not, by itself, extend the size of a file. If fildes refers to a shared memory object, the result of the lseek() function is unspecified. If fildes refers to a typed memory object, the result of the lseek() function is unspecified. RETURN VALUE Upon successful completion, the resulting offset, as measured in bytes from the beginning of the file, shall be returned. Otherwise, −1 shall be returned, errno shall be set to indicate the error, and the file offset shall remain unchanged.
NAME pread, read — read from a file SYNOPSIS #include <unistd.h> ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset); ssize_t read(int fildes, void *buf, size_t nbyte); DESCRIPTION The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf. The behavior of multiple concurrent reads on the same pipe, FIFO, or terminal device is unspecified. Before any action described below is taken, and if nbyte is zero, the read() function may detect and return errors as described below. In the absence of errors, or if error detection is not performed, the read() function shall return zero and have no other results. On files that support seeking (for example, a regular file), the read() shall start at a position in the file given by the file offset associ‐ ated with fildes. The file offset shall be incremented by the number of bytes actually read. Files that do not support seeking—for example, terminals—always read from the current position. The value of a file offset associated with such a file is undefined. No data transfer shall occur past the current end-of-file. If the starting position is at or after the end-of-file, 0 shall be returned. If the file refers to a device special file, the result of subsequent read() requests is implementation-defined. If the value of nbyte is greater than {SSIZE_MAX}, the result is imple‐ mentation-defined. When attempting to read from an empty pipe or FIFO: * If no process has the pipe open for writing, read() shall return 0 to indicate end-of-file. * If some process has the pipe open for writing and O_NONBLOCK is set, read() shall return −1 and set errno to [EAGAIN]. * If some process has the pipe open for writing and O_NONBLOCK is clear, read() shall block the calling thread until some data is written or the pipe is closed by all processes that had the pipe open for writing. When attempting to read a file (other than a pipe or FIFO) that sup‐ ports non-blocking reads and has no data currently available: * If O_NONBLOCK is set, read() shall return −1 and set errno to [EAGAIN]. * If O_NONBLOCK is clear, read() shall block the calling thread until some data becomes available. * The use of the O_NONBLOCK flag has no effect if there is some data available. The read() function reads data previously written to a file. If any portion of a regular file prior to the end-of-file has not been writ‐ ten, read() shall return bytes with value 0. For example, lseek() allows the file offset to be set beyond the end of existing data in the file. If data is later written at this point, subsequent reads in the gap between the previous end of data and the newly written data shall return bytes with value 0 until data is written into the gap. Upon successful completion, where nbyte is greater than 0, read() shall mark for update the last data access timestamp of the file, and shall return the number of bytes read. This number shall never be greater than nbyte. The value returned may be less than nbyte if the number of bytes left in the file is less than nbyte, if the read() request was interrupted by a signal, or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately available for reading. For example, a read() from a file associated with a terminal may return one typed line of data. If a read() is interrupted by a signal before it reads any data, it shall return −1 with errno set to [EINTR]. If a read() is interrupted by a signal after it has successfully read some data, it shall return the number of bytes read. For regular files, no data transfer shall occur past the offset maximum established in the open file description associated with fildes. If fildes refers to a socket, read() shall be equivalent to recv() with no flags set. If the O_DSYNC and O_RSYNC bits have been set, read I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion. If the O_SYNC and O_RSYNC bits have been set, read I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion. If fildes refers to a shared memory object, the result of the read() function is unspecified. If fildes refers to a typed memory object, the result of the read() function is unspecified. A read() from a STREAMS file can read data in three different modes: byte-stream mode, message-nondiscard mode, and message-discard mode. The default shall be byte-stream mode. This can be changed using the I_SRDOPT ioctl() request, and can be tested with I_GRDOPT ioctl(). In byte-stream mode, read() shall retrieve data from the STREAM until as many bytes as were requested are transferred, or until there is no more data to be retrieved. Byte-stream mode ignores message boundaries. In STREAMS message-nondiscard mode, read() shall retrieve data until as many bytes as were requested are transferred, or until a message bound‐ ary is reached. If read() does not retrieve all the data in a message, the remaining data shall be left on the STREAM, and can be retrieved by the next read() call. Message-discard mode also retrieves data until as many bytes as were requested are transferred, or a message boundary is reached. However, unread data remaining in a message after the read() returns shall be discarded, and shall not be available for a subsequent read(), getmsg(), or getpmsg() call. How read() handles zero-byte STREAMS messages is determined by the cur‐ rent read mode setting. In byte-stream mode, read() shall accept data until it has read nbyte bytes, or until there is no more data to read, or until a zero-byte message block is encountered. The read() function shall then return the number of bytes read, and place the zero-byte message back on the STREAM to be retrieved by the next read(), getmsg(), or getpmsg(). In message-nondiscard mode or message-discard mode, a zero-byte message shall return 0 and the message shall be removed from the STREAM. When a zero-byte message is read as the first message on a STREAM, the message shall be removed from the STREAM and 0 shall be returned, regardless of the read mode. A read() from a STREAMS file shall return the data in the message at the front of the STREAM head read queue, regardless of the priority band of the message. By default, STREAMs are in control-normal mode, in which a read() from a STREAMS file can only process messages that contain a data part but do not contain a control part. The read() shall fail if a message con‐ taining a control part is encountered at the STREAM head. This default action can be changed by placing the STREAM in either control-data mode or control-discard mode with the I_SRDOPT ioctl() command. In control- data mode, read() shall convert any control part to data and pass it to the application before passing any data part originally present in the same message. In control-discard mode, read() shall discard message control parts but return to the process any data part in the message. In addition, read() shall fail if the STREAM head had processed an asynchronous error before the call. In this case, the value of errno shall not reflect the result of read(), but reflect the prior error. If a hangup occurs on the STREAM being read, read() shall continue to operate normally until the STREAM head read queue is empty. Thereafter, it shall return 0. The pread() function shall be equivalent to read(), except that it shall read from a given position in the file without changing the file pointer. The first three arguments to pread() are the same as read() with the addition of a fourth argument offset for the desired position inside the file. An attempt to perform a pread() on a file that is incapable of seeking shall result in an error. RETURN VALUE Upon successful completion, these functions shall return a non-negative integer indicating the number of bytes actually read. Otherwise, the functions shall return −1 and set errno to indicate the error. ERRORS These functions shall fail if: EAGAIN The file is neither a pipe, nor a FIFO, nor a socket, the O_NON‐ BLOCK flag is set for the file descriptor, and the thread would be delayed in the read operation. EBADF The fildes argument is not a valid file descriptor open for reading. EBADMSG The file is a STREAM file that is set to control-normal mode and the message waiting to be read includes a control part. EINTR The read operation was terminated due to the receipt of a sig‐ nal, and no data was transferred. EINVAL The STREAM or multiplexer referenced by fildes is linked (directly or indirectly) downstream from a multiplexer. EIO The process is a member of a background process group attempting to read from its controlling terminal, and either the calling thread is blocking SIGTTIN or the process is ignoring SIGTTIN or the process group of the process is orphaned. This error may also be generated for implementation-defined reasons. EISDIR The fildes argument refers to a directory and the implementation does not allow the directory to be read using read() or pread(). The readdir() function should be used instead. EOVERFLOW The file is a regular file, nbyte is greater than 0, the start‐ ing position is before the end-of-file, and the starting posi‐ tion is greater than or equal to the offset maximum established in the open file description associated with fildes. The pread() function shall fail if: EINVAL The file is a regular file or block special file, and the offset argument is negative. The file pointer shall remain unchanged. ESPIPE The file is a pipe, FIFO, or socket. The read() function shall fail if: EAGAIN The file is a pipe or FIFO, the O_NONBLOCK flag is set for the file descriptor, and the thread would be delayed in the read operation. EAGAIN or EWOULDBLOCK The file is a socket, the O_NONBLOCK flag is set for the file descriptor, and the thread would be delayed in the read opera‐ tion. ECONNRESET A read was attempted on a socket and the connection was forcibly closed by its peer. ENOTCONN A read was attempted on a socket that is not connected. ETIMEDOUT A read was attempted on a socket and a transmission timeout occurred. These functions may fail if: EIO A physical I/O error has occurred. ENOBUFS Insufficient resources were available in the system to perform the operation. ENOMEM Insufficient memory was available to fulfill the request. ENXIO A request was made of a nonexistent device, or the request was outside the capabilities of the device. The following sections are informative. EXAMPLES Reading Data into a Buffer The following example reads data from the file associated with the file descriptor fd into the buffer pointed to by buf. #include <sys/types.h> #include <unistd.h> ... char buf[20]; size_t nbytes; ssize_t bytes_read; int fd; ... nbytes = sizeof(buf); bytes_read = read(fd, buf, nbytes); ...
NAME write - write to a file descriptor SYNOPSIS #include <unistd.h> ssize_t write(int fd, const void *buf, size_t count); DESCRIPTION write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd. The number of bytes written may be less than count if, for example, there is insufficient space on the underlying physical medium, or the RLIMIT_FSIZE resource limit is encountered (see setrlimit(2)), or the call was interrupted by a signal handler after having written less than count bytes. (See also pipe(7).) For a seekable file (i.e., one to which lseek(2) may be applied, for example, a regular file) writing takes place at the current file off‐ set, and the file offset is incremented by the number of bytes actually written. If the file was open(2)ed with O_APPEND, the file offset is first set to the end of the file before writing. The adjustment of the file offset and the write operation are performed as an atomic step. POSIX requires that a read(2) which can be proved to occur after a write() has returned returns the new data. Note that not all filesys‐ tems are POSIX conforming. RETURN VALUE On success, the number of bytes written is returned (zero indicates nothing was written). It is not an error if this number is smaller than the number of bytes requested; this may happen for example because the disk device was filled. See also NOTES. On error, -1 is returned, and errno is set appropriately. If count is zero and fd refers to a regular file, then write() may return a failure status if one of the errors below is detected. If no errors are detected, or error detection is not performed, 0 will be returned without causing any other effect. If count is zero and fd refers to a file other than a regular file, the results are not speci‐ fied. ERRORS EAGAIN The file descriptor fd refers to a file other than a socket and has been marked nonblocking (O_NONBLOCK), and the write would block. See open(2) for further details on the O_NONBLOCK flag. EAGAIN or EWOULDBLOCK The file descriptor fd refers to a socket and has been marked nonblocking (O_NONBLOCK), and the write would block. POSIX.1-2001 allows either error to be returned for this case, and does not require these constants to have the same value, so a portable application should check for both possibilities. EBADF fd is not a valid file descriptor or is not open for writing. EDESTADDRREQ fd refers to a datagram socket for which a peer address has not been set using connect(2). EDQUOT The user's quota of disk blocks on the filesystem containing the file referred to by fd has been exhausted. EFAULT buf is outside your accessible address space. EFBIG An attempt was made to write a file that exceeds the implementa‐ tion-defined maximum file size or the process's file size limit, or to write at a position past the maximum allowed offset. EINTR The call was interrupted by a signal before any data was writ‐ ten; see signal(7). EINVAL fd is attached to an object which is unsuitable for writing; or the file was opened with the O_DIRECT flag, and either the address specified in buf, the value specified in count, or the current file offset is not suitably aligned. EIO A low-level I/O error occurred while modifying the inode. ENOSPC The device containing the file referred to by fd has no room for the data. EPERM The operation was prevented by a file seal; see fcntl(2). EPIPE fd is connected to a pipe or socket whose reading end is closed. When this happens the writing process will also receive a SIG‐ PIPE signal. (Thus, the write return value is seen only if the program catches, blocks or ignores this signal.) Other errors may occur, depending on the object connected to fd. CONFORMING TO SVr4, 4.3BSD, POSIX.1-2001. Under SVr4 a write may be interrupted and return EINTR at any point, not just before any data is written.
NAME dup, dup2, dup3 - duplicate a file descriptor SYNOPSIS #include <unistd.h> int dup(int oldfd); int dup2(int oldfd, int newfd); #define _GNU_SOURCE /* See feature_test_macros(7) */ #include <fcntl.h> /* Obtain O_* constant definitions */ #include <unistd.h> int dup3(int oldfd, int newfd, int flags); DESCRIPTION The dup() system call creates a copy of the file descriptor oldfd, using the lowest-numbered unused descriptor for the new descriptor. After a successful return, 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 descrip‐ tors, 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. dup2() The dup2() system call performs the same task as dup(), but instead of using the lowest-numbered unused file descriptor, it uses the descrip‐ tor number specified in newfd. If the descriptor newfd was previously open, it is silently closed before being reused. The steps of closing and reusing the file descriptor newfd are per‐ formed atomically. This is important, because trying to implement equivalent functionality using close(2) and dup() would be subject to race conditions, whereby newfd might be reused between the two steps. Such reuse could happen because the main program is interrupted by a signal handler that allocates a file descriptor, or because a parallel thread allocates a file descriptor. Note the following points: * If oldfd is not a valid file descriptor, then the call fails, and newfd is not closed. * If oldfd is a valid file descriptor, and newfd has the same value as oldfd, then dup2() does nothing, and returns newfd. dup3() dup3() is the same as dup2(), except that: * The caller can force the close-on-exec flag to be set for the new file descriptor by specifying O_CLOEXEC in flags. See the descrip‐ tion of the same flag in open(2) for reasons why this may be useful. * If oldfd equals newfd, then dup3() fails with the error EINVAL. RETURN VALUE On success, these system calls return the new descriptor. On error, -1 is returned, and errno is set appropriately. ERRORS EBADF oldfd isn't an open file descriptor. EBADF newfd is out of the allowed range for file descriptors (see the discussion of RLIMIT_NOFILE in getrlimit(2)). EBUSY (Linux only) This may be returned by dup2() or dup3() during a race condition with open(2) and dup(). EINTR The dup2() or dup3() call was interrupted by a signal; see sig‐ nal(7). EINVAL (dup3()) flags contain an invalid value. EINVAL (dup3()) oldfd was equal to newfd. EMFILE The per-process limit on the number of open file descriptors has been reached (see the discussion of RLIMIT_NOFILE in getr‐ limit(2)). VERSIONS dup3() was added to Linux in version 2.6.27; glibc support is available starting with version 2.9. CONFORMING TO dup(), dup2(): POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD. dup3() is Linux-specific.
NAME truncate, ftruncate - truncate a file to a specified length SYNOPSIS #include <unistd.h> #include <sys/types.h> int truncate(const char *path, off_t length); int ftruncate(int fd, off_t length); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): truncate(): _BSD_SOURCE || _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED || /* Since glibc 2.12: */ _POSIX_C_SOURCE >= 200809L ftruncate(): _BSD_SOURCE || _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED || /* Since glibc 2.3.5: */ _POSIX_C_SOURCE >= 200112L DESCRIPTION The truncate() and ftruncate() functions cause the regular file named by path or referenced by fd to be truncated to a size of precisely length bytes. If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is extended, and the extended part reads as null bytes ('\0'). The file offset is not changed. If the size changed, then the st_ctime and st_mtime fields (respec‐ tively, time of last status change and time of last modification; see stat(2)) for the file are updated, and the set-user-ID and set-group-ID mode bits may be cleared. With ftruncate(), the file must be open for writing; with truncate(), the file must be writable. RETURN VALUE On success, zero is returned. On error, -1 is returned, and errno is set appropriately. ERRORS For truncate(): EACCES Search permission is denied for a component of the path prefix, or the named file is not writable by the user. (See also path_resolution(7).) EFAULT The argument path points outside the process's allocated address space. EFBIG The argument length is larger than the maximum file size. (XSI) EINTR While blocked waiting to complete, the call was interrupted by a signal handler; see fcntl(2) and signal(7). EINVAL The argument length is negative or larger than the maximum file size. EIO An I/O error occurred updating the inode. EISDIR The named file is a directory. ELOOP Too many symbolic links were encountered in translating the pathname. ENAMETOOLONG A component of a pathname exceeded 255 characters, or an entire pathname exceeded 1023 characters. ENOENT The named file does not exist. ENOTDIR A component of the path prefix is not a directory. EPERM The underlying filesystem does not support extending a file beyond its current size. EPERM The operation was prevented by a file seal; see fcntl(2). EROFS The named file resides on a read-only filesystem. ETXTBSY The file is a pure procedure (shared text) file that is being executed. For ftruncate() the same errors apply, but instead of things that can be wrong with path, we now have things that can be wrong with the file descriptor, fd: EBADF fd is not a valid descriptor. EBADF or EINVAL fd is not open for writing. EINVAL fd does not reference a regular file. EINVAL or EBADF The file descriptor fd is not open for writing. POSIX permits, and portable applications should handle, either error for this case. (Linux produces EINVAL.) CONFORMING TO POSIX.1-2001, POSIX.1-2008, 4.4BSD, SVr4 (these calls first appeared in 4.2BSD).
NAME sync — schedule file system updates SYNOPSIS #include <unistd.h> void sync(void); DESCRIPTION The sync() function shall cause all information in memory that updates file systems to be scheduled for writing out to all file systems. The writing, although scheduled, is not necessarily complete upon return from sync(). RETURN VALUE The sync() function shall not return a value.
fsync 与fdatasync
NAME fsync, fdatasync - synchronize a file's in-core state with storage device SYNOPSIS #include <unistd.h> int fsync(int fd); int fdatasync(int fd); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): fsync(): _BSD_SOURCE || _XOPEN_SOURCE || /* since glibc 2.8: */ _POSIX_C_SOURCE >= 200112L fdatasync(): _POSIX_C_SOURCE >= 199309L || _XOPEN_SOURCE >= 500 DESCRIPTION fsync() transfers ("flushes") all modified in-core data of (i.e., modi‐ fied buffer cache pages for) the file referred to by the file descrip‐ tor fd to the disk device (or other permanent storage device) so that all changed information can be retrieved even after the system crashed or was rebooted. This includes writing through or flushing a disk cache if present. The call blocks until the device reports that the transfer has completed. It also flushes metadata information associ‐ ated 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 modifica‐ tion; see stat(2)) do not require flushing because they are not neces‐ sary 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() is to reduce disk activity for applications that do not require all metadata to be synchronized with the disk. RETURN VALUE On success, these system calls return zero. On error, -1 is returned, and errno is set appropriately. ERRORS EBADF fd is not a valid open file descriptor. EIO An error occurred during synchronization. EROFS, EINVAL fd is bound to a special file which does not support synchro‐ nization. CONFORMING TO POSIX.1-2001, POSIX.1-2008, 4.3BSD.
参见:link
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。