François Trahay
Buffered I/O
→ a buffered I/O ≠ an operation on the disk
fopen, fread, fscanf,
fwrite, fprintf, etc.FILE*Unbuffered I/O
open, read, write,
etc.intint open(const char *path, int flags, mode_t mode)
returns f_id
flags can take one of the following values:
O_RDONLY: read onlyO_WRONLY: write onlyO_RDWR: read and writeAdditional flags:
O_APPEND: append data (write at the end of the
file)O_TRUNC: truncate (empty) the file when opening itO_CREAT: creation if the file does not exist. The
permissions are (mode & ∼ umask)O_SYNC: open file in synchronous write modeO_NONBLOCK (ot O_NDELAY):
open and subsequent operations performed on the descriptor
will be non-blocking.int close(int desc)ssize_t read(int fd, void *buf, size_t count)
returns the number of bytes successfully read
When read returns, the buf zone
contains the read data;
In the case of a file, the number of bytes read may not be be
equal to count:
ssize_t write(int fd, const void *buf, size_t count)
return the number of bytes written
In the case of a file, the return value (without error) of the write operation means that:
O_SYNC was
specify at file open;O_SYNC was
specified.In the case of a file, a number of bytes written that is
different from count means an error (e.g. No space left on
device)
int dup(int old_fd)
new_fdold_fdint dup2(int old_fd, int new_fd)
new_fd to become a synonym of
the old_fd descriptor. If the descriptor
new_fd is not available, the system first closes
close(new_fd)struct flock {
short l_type;
short l_whence;
off_t l_start;
off_t l_len;
};
int fcntl(int fd, F_SETLK, struct flock*lock);
Locks are attached to an inode. So locking a file affects all file descriptors (and therefore all open files) corresponding to this inode
A lock is the property of a process: this process is the only one authorized to modify or remove it
Locks have a scope of [integer1 : integer2] or [integer : ∞]
Locks have a type:
F_RDLCK: allows concurrent read accessF_WRLCK: exclusive accessoff_t lseek(int fd, off_t unOffset, int origine)
return the new offset
allows to handle the offset of the file
Warning ! Race condition if several threads manipulate the file
Solutions:
pread or pwrite instead of
lseek + read or lseek + writeint posix_fadvise(int fd, off_t offset, off_t len, int advice)
POSIX_FADV_SEQUENTIAL,
POSIX_FADV_RANDOM, POSIX_FADV_WILLNEEDint aio_read(struct aiocb *aiocbp);
int aio_write(struct aiocb *aiocbp);
int aio_suspend(const struct aiocb * const aiocb_list[],
int nitems,
const struct timespec *timeout);
int aio_error(const struct aiocb *aiocbp);
void *mmap(void *addr,
size_t length,
int prot,
int flags,
int fd,
off_t offset);
int munmap(void *addr, size_t length);