Thu 8 Feb 15:43:18 GMT 2018node
Part III網絡
interaction and communication between Programs數據結構
--------------------------------------------------------ide
chapter 10 System-Level I/O函數
10.1 Unix I/Oorm
<unistd.h> : STDIN_FILENO STDOUT_FILENO STDERR_FILENOip
10.2 filesget
對內核而言,文本文件和二進制文件沒有區別string
10.3 open and close filesit
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(char *filename, int flags, mode_t mode);
flags:
+ O_RDONLY
+ O_WRONLY
+ O_RDWR
for write:
+ O_CREAT
+ O_TRUNC
+ O_APPEND
fd = open("foo.txt",O_WRONLY|O_APPEND,O);
umask(O_WRONLY);
#include <unistd.h>
int close(int fd);
10.4 read and write files
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t n);
ssize_t write(int fd, const void *buf,size_t n);
lseek function set position.
In the x86-64, size_t means unsigned long and ssize_t
means long type.
10.5 用RIO包健壯地讀寫(Robust I/O)
RIO提供兩類不一樣函數:
+ 無緩衝的輸入輸出函數
對二進制讀寫網絡有用
+ 帶緩衝的輸入輸出函數
對文件中讀寫有用
10.6 讀取文件元數據
應用程序能經過調用stat和fstat函數,檢索到關於文件的信
息(有時也稱爲文件的元數據)。
10.7 讀取目錄內容
#include <sys/types.h>
#include <dirent.h>
+ DIR *opendir( const char *name);
+ struct dirent *readdir(DIR *dirp);
+ struct dirent {
ino_t d_ino; // inode number
char d_name[256]; // filename
};
+ int closedir(DIR *dirp);
10.8 共享文件
內核用三個相關的數據結構來表示打開的文件:
1. 描述符表(descriptor table).
Each process has its own descriptor tabel.
2. 文件表(file table).
Each file table entry consists of the current
file position, a reference count of the number
of descriptor entries that currently point to it.
The kernel will not delete the file table entry
until its reference count is Zero.
3. v-node表。
Like the file table, the v-node table is shared
by all processes. Each each contains most of the
information in the 'stat' structure, including
the st_mode and st_size members.
10.9 I/O Redirection
#include <unistd.h>
int dup2(int oldfd, int newfd);
10.10 Standard I/O
The libary(libc) provides functions for opening and
closing files( fopen and fclose ), reading and writing
bytes( fread and fwrite ), reading and writing strings
( fgets and fputs ), and sophisticated formatted I/O
( scanf and printf ).
To the programmer, a stream is a pointer to a
structure of type FILE.
10.11 綜合:我該使用哪些I/O函數