Unix I/O Overview
1.A linux file is a sequence of m bytes
B0,B1..Bm-1
2.all I/O devices and even the kernel are represented as files
/dev/sda2 (/usr disk partition)
/dev/tty2 (terminal)
File Types
1.regular file
2.directory
3.socket for communicating with a process on another machine
regular files
Kernel doesn’t know the difference between text files and regular files
pathname
absolute pathname
starts with ‘/‘ and denotes path from root
/home/droh/a.c
relative pathname
../home/droh/a.c
open&closing file
Reading Files
Writing Files
Simple Unix I/O example
bad case
Each while loop, execute 2 operating system function,that means you have to go to the kernel,go through,context switch,do whatever you wants,then switch back. in a word,it is too expensive.
1 | #include "csapp.h" |
short counts
File Metadata
File Sharing
fork
内核用三个相关的数据结构来表示打开的文件
1.每个进程都有它独立的描述符表,它的表项是由进程打开的文件描述符来索引的,每个打开的描述符表项指向文件表一个表项。
2.文件表。是所有进程共享的,保存当前文件位置,引用计数(当前指向该表项的描述符表项数),以及一个指向vnode表对应表项的指针
3.vnode表,所有进程共享
I/O Redirection
steps 1
steps 2
1 |
|
就是把重定向标准输入到描述符5
一些例子
fd3重定向到了fd2,所以他们指向同样的open file table项,c2是第一个字符a,而c3在此基础上读下一个字符,所以是b。