星期一, 12月 07, 2009

Simple Shell in Unix

用C練習了一個簡單的shell,在這做一下重點筆記。


#include
...

#define MAXLINE 80
...

void handle_SIGINT();
...

int hindex;
...

void handle_SIGINT(){
int i = hindex - 1;
char tmp[MAXLINE];
write(STDOUT_FILENO, "\nHistroy:\n", 10);
for(;i > (hindex - 10) && i >= 0;i--){
...
}

signal(SIGINT, handle_SIGINT);
write(STDOUT_FILENO, "\n COMMAND->", 11);
}

void processBuffer(char inputBuffer[], char* args[], int length, int* background){
/* 處理inputBuffer,把他變成一個一個arg儲存在args中 */
}

void readHistory(char* args[], char fletter, int* background){
int i;
for(i = hindex - 1; i >= (hindex-10); i--)
if(*history[i] == fletter) break;
strcpy(history[hindex - 1], history[i]);
processBuffer(history[i], args, strlen(history[i]), background);
}


void setup(char inputBuffer[], char* args[], int* background){
/* 讀入user input並且呼叫processBuffer負責處理,順便紀錄在history中 */
}

int main(void){
char inputBuffer[MAXLINE];
int background; /* indicate if the program run in background when '&' at the end */
char* args[MAXLINE/2 + 1];

hindex = 0; /* initilize the history index which point to the next history storage */


while(1){
background = 0;
printf(" COMMAND->");
fflush(stdout);
signal(SIGINT, handle_SIGINT); /* set up, when program received the control + c
it will invoke the handle_SIGINT function */

setup(inputBuffer, args, &background);
if(!fork()){
execvp(args[0], args);
}else{
if(!background)
wait();
}
}
}




signal(SIGINT, handle_SIGINT);

是收到signal時,會呼叫哪個function來處理。

原始檔案連結:Link

沒有留言: