最近在看大神W.Richard Stevens
的Advanced Programming in the UNIX? Environment
,簡稱APUE
。
以下是我寫的讀書筆記。
- File I/O
UNIX下一切皆文件,內(nèi)核通過文件描述符來訪問文件。
每個進程默認打開3個file descriptor: STDIN_FILENO
, STDOUT_FILENO
, STDERR_DILENO
每個進程都有一個entry in process table entry
,每個entry
可以看作是一個(python中的)字典,字典的key是文件描述符,value是一個Tuple,Tuple中的元素為(file descriptor flags
, A pointer to a file table entry
)
內(nèi)核為所有打開的文件維護一個file table
, 其中的每個entry包含:
(a) The file status flags for the file, such as read, write, append, sync, and
nonblocking;
(b) The current file offset
(c) A pointer to the v-node table entry for the file
Each open file (or device) has a v-node structure that contains information about the type of file and pointers to functions that operate on the file.
每個打開的文件(或設備)都有一個v-node
的結構,其包含了文件的元信息。(Linux has no v-node.)
用圖表示:
- 習題 3.6:
If you open a file for read–write with the append flag, can you still read from anywhere in the file using lseek? Can you use lseek to replace existing data in the file? Write a program to verify this.
答:可以。
舉個例子:有如下兩個程序。
3.6_1.c, 編譯為w
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int fd, i;
char buf[] = "123456789abcdefghijklmnopqrstuvwxyz";
fd = open("a.txt", O_RDWR| O_CREAT | O_APPEND);
if (fd == -1) {
perror("open");
exit(1);
}
for (i=0; i<strlen(buf); i++) {
write(fd, buf+i, 1);
sleep(3);
}
return 0;
}
3.6_2.c, 編譯為r
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFSIZE 32
int main(int argc, char const *argv[])
{
int fd;
fd = open("a.txt", O_WRONLY);
char buf[BUFSIZE] = "0";
if (fd == -1) {
perror("open");
exit(1);
}
lseek(fd, 0, SEEK_SET);
write(fd, buf, 1);
printf("The written char is %c\n", buf[0]);
read(fd, buf, 1);
printf("The read char is %c\n", buf[0]);
return 0;
}
我們先運行w,(等幾秒)然后再運行r。這里會生成a.txt
文件,我們可以看看文件的內(nèi)容:
0234567
程序3.6_2.c
lseek到文件開頭處 并且替換了文件開頭的1
。
這說明不同進程間是可以共享文件的,如果有多個進程同時操作文件,可能會造成文件內(nèi)容的損壞。