[Unix] 輸入internal node路徑建立binary tree
Unix programming 重點之一就是 fork 跟 wait 的理解
這次的程式是要藉由輸入 0 或 1 來代表左子樹或右子樹
範例:
$ ./a.out ""
I'm 1054, my parent is 1053
I'm 1055, my parent is 1053
I'm 1053, my two children is 1054 and 1055
$ ./a.out "1" I'm 1057, my parent is 1056
I'm 1059, my parent is 1058
I'm 1060, my parent is 1058
I'm 1058, my two children is 1059 and 1060
I'm 1056, my two children is 1057 and 1058
$ ./a.out "10"
I'm 1062, my parent is 1061
I'm 1065, my parent is 1064
I'm 1066, my parent is 1064
I'm 1064, my two children is 1065 and 1066
I'm 1067, my parent is 1063
I'm 1063, my two children is 1064 and 1067
I'm 1061, my two children is 1062 and 1063
$
C :
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/wait.h> int build_tree(char *tree_path); int main(int argc, char *argv[]) { int i,check; char *tree_path = NULL; tree_path = argv[1]; check = build_tree(tree_path); return 0; } int build_tree(char *tree_path) // path is a string include only '0' & '1' { pid_t childpid, Lchild=0, Rchild=0; int i; // each parent have two children for(i=0; i<2; ++i){ childpid = fork(); if(i == 0) Lchild= (long)childpid; else if(i == 1) Rchild= (long)childpid; // child process if(childpid == 0){ // path correct if(i == tree_path[0]-'0'){ tree_path++; // renew the path i=-1; // reset child_count continue; } // path incorrect: end of child process else{ printf("I'm %ld, my parent is %ld\n", (long)getpid(), (long)getppid()); return; } } wait(NULL); } // parent process if(Lchild !=0 && Rchild !=0) printf("I'm %ld, my two children is %ld and %ld\n", (long)getpid, Lchild, Rchild); return 1; }
當我們要建立 binary tree 時, 利用遞迴去思考是沒錯的
但是我們可以不用寫出一個 recursive function 去執行
因為 Shell 就會自動地用 recursive 的方式產生跟結束 parent & child process
fork 之後因為有左右子樹, 所以記得要先把child pid 先存起來
然後進入 child process 判斷路徑是否正確
當路徑正確時, binary tree 必須繼續向下生長
也因此必須更新要判斷的路徑, 以及重新計算子樹數量, 也就是 child process 的數量
當路徑錯誤時, 代表該 child process 是 external node
因此必須結束 child process 返回 parent process
查看原文 >>