[英]Explain pipe and fork output
I am dealing with pipe and fork in Linux for the first time and I would be happy if someone could explain to me the output of the following program: (which line of code causes the output and is it through the son process or the parent process )
int main(){ //1
int ipc[2]; //2
pipe(ipc); //3
write(2, "start\n", 6); //4
if (fork()) { //5
sleep(1); //6
char c; //7
do { //8
read(ipc[0], &c, 1); //9
write(1, &c, 1); //10
} while (c != '\n'); //11
write(1, "if\n", 3); //12
waitpid(-1, NULL, 0); //13
} //14
else { //15
write(ipc[1], "else1\n", 6); //16
write(1, "else2\n", 6); //17
} //18
write(1, "done\n", 5); //19
return 0; //20
} //21
程序的output為:
start
else2
done
else1
if
done
fork()
創建一個執行與原始進程相同代碼的子進程。 如果成功,您的兩個進程之間的唯一區別是:
fork
會返回一個非零值(即子進程的id)fork
將返回一個零值所以,換句話說:當你寫:
if (fork()) {
// Block "If"
} else {
// Block "Else"
}
原始進程將執行“block if”,子進程將執行“block else”。
pipe
返回兩個文件描述符,一個可用於寫入 pipe,另一個可用於從 pipe 中讀取。 所以當你寫:
int ipc[2];
pipe(ipc);
當你閱讀ipc[0]
時,你在ipc[1]
中寫的任何內容都可以被閱讀。 換句話說,這是在fork
創建的兩個進程之間進行通信的好方法。
在您的示例中,子進程(在“else”中)在ipc[1]
中寫入數據,而原始進程(在“if”中)讀取它。
您創建了一個子進程在 pipe 中寫入數據,而您的原始進程從 pipe 中讀取數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.