Xv6 管道
Xv6 管道
參考: xv6-riscv-book 1.3 Pipes
文章目錄
- Xv6 管道
- pipe
- 管道 V.S. 臨時(shí)文件
pipe
Xv6 系統(tǒng)調(diào)用 pipe() 來(lái)創(chuàng)建管道。管道類(lèi)似于 Go 語(yǔ)言中的 chan。在 Shell 里我們用 | 表示管道,對(duì)于命令: echo "hello world" | wc,可以用如下代碼實(shí)現(xiàn):
// upipe.c // // Runs the program wc with standard input connected to the read end of a pipe.#include "kernel/types.h" #include "kernel/stat.h" #include "user/user.h"int main() {int p[2]; // file descriptors for the pipechar *argv[2];argv[0] = "wc";argv[1] = 0; // NULLpipe(p); // creates a new pipe: records the read and write file descriptors in the array pif (fork() == 0) {// redirectionclose(0);dup(p[0]); // stdin = <- pipeclose(p[0]);close(p[1]);exec("wc", argv);} else {close(p[0]);write(p[1], "hello world\n", 12); // pipe <- strclose(p[1]);}exit(0); }編譯運(yùn)行:
$ upipe 1 2 12Xv6 sh 里的管道處理實(shí)現(xiàn)其實(shí)就和這段代碼類(lèi)似:fork 兩個(gè)進(jìn)程,分別重定向標(biāo)準(zhǔn)輸出 or 輸入、運(yùn)行管道左右兩邊的命令。詳見(jiàn) user/sh.c:100。
管道 V.S. 臨時(shí)文件
用管道與用臨時(shí)文件,使用上似乎區(qū)別不大:
# 管道 echo "hello world" | wc # 臨時(shí)文件 echo hello world >/tmp/xyz; wc </tmp/xyz但管道更好:
- 管道會(huì)自動(dòng)清理(臨時(shí)文件要手動(dòng)刪除)
- 管道可以放任意長(zhǎng)度的數(shù)據(jù)流(臨時(shí)文件需要有足夠的磁盤(pán)空間)
- 管道可以并行運(yùn)行(臨時(shí)文件只能一個(gè)運(yùn)行完,第二個(gè)再開(kāi)始)
- 在處理進(jìn)程間通信問(wèn)題時(shí),管道的阻塞式讀寫(xiě)比用非阻塞的臨時(shí)文件方便。
EOF
# By CDFMLR 2021-02-20 echo "See you. 🪐"
頂部圖片來(lái)自于小歪API,系隨機(jī)選取的圖片,僅用于檢測(cè)屏幕顯示的機(jī)械、光電性能,與文章的任何內(nèi)容及觀點(diǎn)無(wú)關(guān),也并不代表本人局部或全部同意、支持或者反對(duì)其中的任何內(nèi)容及觀點(diǎn)。如有侵權(quán),聯(lián)系刪除。
總結(jié)
- 上一篇: 开始时间小于 结束时间 js_DNF分享
- 下一篇: From 7.8 To 7.14