CSAPP-UNIX/IO

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)

filename aady exists, renamed

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

upload succsful

open&closing file

upload successul

upload suessful

Reading Files

upload succful

Writing Files

filenameady exists, renamed

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
2
3
4
5
6
7
8
9
10
#include "csapp.h"

int main(void)
{
char c;

while(Read(STDIN_FILENO, &c, 1) != 0)
Write(STDOUT_FILENO, &c, 1);
exit(0);
}

short counts

filename y exists, renamed

File Metadata

upload essful

File Sharing

upload succesul

filename ady exists, renamed

fork

upload scessful

filename aldy exists, renamed

内核用三个相关的数据结构来表示打开的文件

1.每个进程都有它独立的描述符表,它的表项是由进程打开的文件描述符来索引的,每个打开的描述符表项指向文件表一个表项。

2.文件表。是所有进程共享的,保存当前文件位置,引用计数(当前指向该表项的描述符表项数),以及一个指向vnode表对应表项的指针

3.vnode表,所有进程共享

I/O Redirection

upload cessful

steps 1

upload sucessful

steps 2

upload essful

1
2

fd(5,0)

就是把重定向标准输入到描述符5

一些例子

upload succeful

fd3重定向到了fd2,所以他们指向同样的open file table项,c2是第一个字符a,而c3在此基础上读下一个字符,所以是b。