系統級 I/O練習題 (Practice - System-Level IO)


Question 1 - 最小描述子規則 [recall]

一個由 shell 建立的 process 執行 fd1 = Open("foo.txt", O_RDONLY, 0);,接著 Close(fd1);,再執行 fd2 = Open("baz.txt", O_RDONLY, 0);
印出的 fd2 是多少?為什麼?


Question 2 - read 回傳值語意 [recall]

ssize_t read(int fd, void *buf, size_t n) 的三種回傳值各代表什麼?檔案結尾有沒有「EOF 字元」?


Question 3 - short count 成因 [recall]

read/write 傳輸的位元組數少於要求量稱為 short count。它是不是錯誤?列出三種會產生 short count 的情境。


Question 4 - open flags [recall]

說明 O_CREATO_TRUNCO_APPEND 三個 flag 的語意。O_APPEND 是「open 時把位置移到檔尾一次」嗎?


Question 5 - RIO 無緩衝函式 [recall]

rio_readnrio_writen 各在什麼情況下會回傳 short count?若 read 被 signal handler 中斷(errno == EINTR),RIO 如何處理?


Question 6 - rio_readlineb 行為 [recall]

rio_readlineb(rp, usrbuf, maxlen) 最多讀入幾個 bytes?讀到的行包含什麼?遇到超過 maxlen 的長行會怎樣?


Question 7 - kernel 三張表 [recall]

kernel 用哪三個資料結構表示 open files?哪一張是 per-process,哪兩張全系統共享?file table entry 何時被刪除?


Question 8 - dup2 語意 [recall]

dup2(oldfd, newfd) 做了什麼?若 newfd 原本已開啟會如何?要把 standard input 重導向到 descriptor 5,該怎麼呼叫?


Question 9 - I/O 套件選用準則 [recall]

依 CSAPP 的三條準則:(1) 磁碟與終端機 I/O 首選哪套?(2) 為什麼不能用 scanfrio_readlineb 讀 binary 檔?(3) network socket 上該用哪套?


Question 10 - 同檔兩次 open [application]

檔案 foobar.txt 內容為 6 個 ASCII 字元 foobar。以下程式輸出為何?

int fd1 = Open("foobar.txt", O_RDONLY, 0);
int fd2 = Open("foobar.txt", O_RDONLY, 0);
char c;
Read(fd1, &c, 1);
Read(fd2, &c, 1);
printf("c = %c\n", c);

Question 11 - fork 後共享 position [application]

同樣的 foobar.txt(內容 foobar),以下程式輸出為何?

int fd = Open("foobar.txt", O_RDONLY, 0);
char c;
if (Fork() == 0) {
    Read(fd, &c, 1);
    exit(0);
}
Wait(NULL);
Read(fd, &c, 1);
printf("c = %c\n", c);

Question 12 - dup2 後讀取 [application]

同樣的 foobar.txt(內容 foobar),以下程式輸出為何?

int fd1 = Open("foobar.txt", O_RDONLY, 0);
int fd2 = Open("foobar.txt", O_RDONLY, 0);
char c;
Read(fd2, &c, 1);
Dup2(fd2, fd1);
Read(fd1, &c, 1);
printf("c = %c\n", c);

Question 13 - dup2(4,1) 的表結構變化 [analysis]

初始狀態:fd 1(stdout)指向 File A(終端機,refcnt=1),fd 4 指向 File B(磁碟檔,refcnt=1)。呼叫 dup2(4, 1) 後,分析:(a) 兩個檔案的 refcnt 各變成多少?(b) File A 的 file table entry 命運如何?(c) fd 1 與 fd 4 是否共享 file position?


Question 14 - 為何 socket 不能用 standard I/O [analysis]

Standard I/O stream 是 full duplex,理論上一個 stream 就能對 socket 讀寫。請分析:(1) stream 的兩條 I/O 順序限制是什麼?(2) 為何在 socket 上無法滿足?(3) 對同一 socket descriptor 開兩個 stream(fdopen 一讀一寫)為什麼仍是災難配方?