我仍然在學習編寫簡單的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任何意見。謝謝。
你也應該檢查realloc的返回值,它並不總是成功 –
你可以分享你的完整代碼,它有main()來測試這些函數嗎? – cm161
@ cm161是的,我只是編輯線程 – John