2017-02-17 125 views
-1

我想在c中編寫我自己的簡單shell。 當我在shell中輸入一個命令(例如ls)時,我得到分段錯誤(核心轉儲)。 也許問題出在主要的爭論中?分割故障(核心轉儲)在我自己的shell中c

我找不到問題所在。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <sys/wait.h> 
#include <unistd.h> 

#define BUFFER_SIZE 512 



char *readline(void){ 

    char* line; 
    if(!fgets(line, BUFFER_SIZE, stdin)){ 
     exit; 
    } 
    size_t length=strlen(line); 
    if (line[length-1]== '\n'){ 
     line[length-1]='\0'; 
    } 
    if(strcmp(line, "exit") ==0){ 
     exit; 
    } 
    return line; 
} 



char **split_line(char *line){ 
    char* tokens[100]; 
    char* token; 
    int i=0; 

    token=strtok(line," "); 

    while(token !=NULL){ 
     tokens[i] = token; 
     token=strtok(NULL, " "); 
    } 
    tokens[i]=NULL; 
    return tokens; 
} 



int exec_line(char **args){ 
    pid_t pid, wpid; 
    char path[40]; 
    int status; 

    strcpy(path, "/bin/"); 
    strcat(path, args[0]); 

    pid=fork(); 
    if(pid==0){ 
     if (execvp(path, args)== -1){ 
      printf("Child process could not do execvp \n"); 
     } 
     exit(EXIT_FAILURE); 

    }else{ 
     do{ 
      wpid=waitpid(pid, &status, WUNTRACED); 
     }while (!WIFEXITED(status) && !WIFSIGNALED(status)); 
    } 
    return 1; 

} 


void lloop(void){ 
     char *line; 
     char **args; 
     int status; 

     do{ 
       printf("my_shell> "); 
       line=readline(); 
       args=split_line(line); 
       status=exec_line(args); 

       free(line); 
       free(args); 
     }while(status); 
} 


int main(){ 

     lloop(); 

     return EXIT_SUCCESS; 
} 
+7

'char * line;如果(!fgets(line,BUFFER_SIZE,stdin))...'沒有分配內存......崩潰。 –

+1

你應該看看[適當的C格式化](// prohackr112.tk/pcf)。或者學習如何[徹底混淆你的代碼](// prohackr112.tk/guide/coding/proper-c-obfuscation)。 –

+1

順便說一句'exit;'是一個語法錯誤。它需要像'exit(EXIT_FAILURE);'這是你的代碼嗎? –

回答

0

問題1:你不能寫的exit();exit;代替

問題2:分割線功能你寫

while(token !=NULL){ tokens[i] = token; token=strtok(NULL, " ");}

不提倡i

問題3:exec_line功能你寫strcat(path, args[0]);

args是一個指向 '串',而不是一個真正的 '字符串'。

問題4:上,你沒有給他一個的malloc的指針從來不使用免費

the malloc函數還在保存的地方寫了_free _function的東西。

這是一個未定義的行爲

+0

你是什麼意思「沒有宣傳'我'」?你的意思是'i'從來沒有增加索引下一個數組元素? –

+0

我的意思是沒有'i ++' –