[問題] if statement with fork()
最近小弟在讀OS, 用C++在ubuntu上做了一些練習, 發現一個很奇怪的地方
code1跟code2差別在else statement, 其中1代表一個process(包含test2自己)
但code1只是多了一個else卻造成output有8個1(比code2多了2個), stack overflow
上面也沒有類似例題, 想了滿久也不確定是什麼機制造成else那邊會再多生出2個
process, 先謝謝大家
[Code1_output: 11111111]
void test2(){
int i;
fork();
if(fork()>0){
fork();
}
else if(fork()==0){}
cout<<" 1 "; //輸出一個1代表1個process
}
[Code2_output: 111111]
void test2(){
int i;
fork();
if(fork()>0){
fork();
}
// else if(fork()==0){}
cout<<" 1 "; //輸出一個1代表1個process
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.251.40.176
※ 文章網址: https://www.ptt.cc/bbs/Linux/M.1500799347.A.B73.html
※ 編輯: j611062000 (111.251.40.176), 07/23/2017 16:44:42
→
07/23 19:21, , 1F
07/23 19:21, 1F
推
07/23 21:26, , 2F
07/23 21:26, 2F
→
07/23 21:26, , 3F
07/23 21:26, 3F
推
07/23 22:35, , 4F
07/23 22:35, 4F
推
07/24 00:19, , 5F
07/24 00:19, 5F
→
07/24 09:35, , 6F
07/24 09:35, 6F
謝謝各位的建議
1.謝謝a大解了我的盲點, 我之前一直沒考慮到,else if 也會執行fork
2.回K大, 的確我看stack overflow上面大家都照你的邏輯這樣寫, 這題純粹只是作業
做變化
3.個人盲點:除了沒考慮到else if 會啟動fork()之外, 也忽略掉有3個children process
的pid值會變成parent.
以下附上我的邏輯
void test2(){
1 int i;
2 fork(); //f1
3
4 if(fork()>0){ //f2
5 fork(); //f3
6 }
7
8 else if(fork()==0){} //f4
9
10 cout<<" 1 "; //輸出一個1代表1個process
}
test2()執行到的行數
2-->生出child f1 (pid=0),
此時process=test()+f1(pid=0)
4-->test() / f1 分別生出一個f2,
此時process=test()+f1(pid=1)+2個f2(pid=0)
5-->test() / f1 均進入if, 各生出f3(pid=0)
此時process=test()+f1(pid=1)+2個f2(pid=0)+2個f3(pid=0)
6-->test()+f1+2個f3 均執行完if, 所以直接跳到10
此時process=test()+f1(pid=1)+2個f2(pid=0)+2個f3(pid=0)
8-->2個f2進入8之前分別再生出f4(pid=0), 且2個f3的pid分別改為1
此時process=test()+f1(pid=1)+2個f2(pid=1)+2個f3(pid=0)+2個f4(pid=0)
所以process總數為8個
※ 編輯: j611062000 (111.251.40.176), 07/25/2017 00:45:17
→
07/25 10:42, , 7F
07/25 10:42, 7F
Linux 近期熱門文章
21
56
PTT數位生活區 即時熱門文章