2015-11-13 14 views
-2

我仍然在學習編寫簡單的shell。空白線段。故障(編寫自己的shell)

我想讓這個shell允許空行和註釋。

我做了一些編碼,我遇到了一個問題,如果我直接輸入輸入(空白行),它直接seg.fault核心轉儲。

我不確切地知道錯誤在哪裏,因爲我打印所有內容並且一切都很正常。我在這些行中唯一懷疑的是

if (args[0] == NULL || !(strncmp(args[0],"#",1))) { 
    exitstat = 0; 
} 

我從基本的分割命令函數中得到了參數。奇怪的是評論工程很好。

下面是我的函數,用於讀取用戶輸入和拆分它們(如果我沒有弄錯,則記號)。他們是非常基本的,因爲我從互聯網教程學習這些功能。

char *commandInput() { 
    char *command = NULL; 
    ssize_t bufsize = 0; 
    getline(&command, &bufsize, stdin); 
    return command; 
} 

char **splitLine(char *command) { 
    int bufsize = 64, 
    int position = 0; 
    char **tokens = malloc(bufsize * sizeof(char*)); 
    char *token; 

    token = strtok(command, DELIMITER); 
    while (token != NULL) { 
     tokens[position] = token; 
     position++; 

     if (position >= bufsize) { 
      bufsize += 64;  
      tokens = realloc(tokens, bufsize * sizeof(char*)); 
     } 
      token = strtok(NULL, DELIMITER); 
    } 
    tokens[position] = NULL; 
    return tokens; 
} 

任何人都可以幫助我認識是什麼使seg.fault,如果我輸入空行?謝謝。

編輯

我用調試器(最終成功的幾個試用後使用它),它原來的錯誤位於我沒想到會引起任何問題(見行 - -UPDATE ----)。

他們這樣,我處理我commandInput功能是main()功能,我寫

int main() { 
...... 
    char * command = NULL 
    char **args; 
    command = commandInput(); 
    args= splitLine(command); 

    ------------------ UPDATE!(CAUSING ERROR IF STATEMENT) --------------- 
    background = 0 
    numbarguments = 0 

    // Condition to check whether there is a start program running in  backgrond 
    if (!(strncmp(args[numbarguments - 1], "&",1))) { 
     background = 1; 
     args[numbarguments - 1] = NULL; 
    } 

    ---------------------------------------------- 

    if (args[0] == NULL || !(strncmp(args[0],"#",1))) { 
     exitstat = 0; 
    } 
    ....... //(comparing the arguments other than null) 
} 

所以有關,如果條件是造成我seg.fault任何意見。謝謝。

+0

你也應該檢查realloc的返回值,它並不總是成功 –

+0

你可以分享你的完整代碼,它有main()來測試這些函數嗎? – cm161

+0

@ cm161是的,我只是編輯線程 – John

回答

1

您傳遞給分界線的參數被修改。 strtok通過插入\ 0's並返回一個指向子字符串的指針來修改字符串。 strtok返回的內容不是您可以直接存儲以供日後使用的內容,而是您需要複製的內容。

token = strtok(command, DELIMITER); 
while (token != NULL) 
{ 
    tokens[position] = malloc(strlen(token)+1); 
    strcpy(tokesn[position],token); 
... 

所以換句話說,它是不夠的指針數組分配給字符串,你也需要分配空間來容納你用strtok的記號化字符串。


代碼

if (!(strncmp(args[numbarguments - 1], "&",1))) { 
    background = 1; 
    args[numbarguments - 1] = NULL; 
} 

看起來不對,numberarguments最初是0,所以你是比較args[-1]"&"後來分配args[-1] = NULL這可能會導致賽格故障。

+0

這實際上很有意義。但是,它仍然導致seg.fault。我開始思考,我需要使用free()嗎? – John

+1

是的,你總是需要釋放你的malloc/calloc,但是如果你遇到seg錯誤,它與免費無關 –

+0

我編輯了我的問題。我添加另一個信息,我如何處理來自commandInput函數的值 – John