2011-10-12 58 views
1
[...] Preprocesser directives 

void read_command() 
{ 
    int i;        //index to the arrays stored in parameter[] 
    char *cp;        //points to the command[] 
    const char *hash = " ";    //figures out the strings seperated by spaces 
    memset(command, 0, 100);    //Clear the memory for array 
    parameter[0] = "/bn/";    //Initialize the path 

    //Get the user input and check if an input did occur 
    if(fgets(command, sizeof(command), stdin) == NULL) 
    { 
     printf("Exit!\n"); 
     exit(0); 
    } 

    //Split the command and look store each string in parameter[] 
    cp = strtok(command, " ");   //Get the initial string (the command) 
    strcat(parameter[0], cp);    //Append the command after the path 
    for(i = 1; i < MAX_ARG; i++) 
    { 
     cp = strtok(NULL, " ");   //Check for each string in the array 
     parameter[i] = cp;    //Store the result string in an indexed off array 
     if(parameter[i] == NULL) 
     { 
      break; 
      cp = NULL; 
     } 
    } 
    //Exit the shell when the input is "exit" 
    if(strcmp(parameter[0], "exit") == 0) 
    { 
     printf("Exit!\n"); 
     exit(0); 
    } 

} 


int main() 
{ 

    [...] 

     read_command(); 
     env = NULL;         //There is no environment variable 

      proc = fork(); 
      if(proc == -1)        //Check if forked properly 
      { 
       perror("Error"); 
       exit(1); 
      } 
      if (proc == 0)        //Child process 
      { 
       execve(parameter[0], parameter, env); //Execute the process 
      } 
      else          //Parent process 
      { 
       waitpid(-1, &status, 0);    //Wait for the child to be done 
      } 

    [...] 
} 

代碼的基本思想是由用戶(在read_command()函數完成的)(例如:ls -l)來讀取輸入命令。然後我將輸入字符串分成小字符串並將它們存儲在一個數組中。重點是將參數[0](例如:ls)中的命令和參數[1,2,3等]中的參數(例如-l)存儲起來。但是,我認爲我錯誤地執行了execve()函數。在C,execve的UNIX簡單殼和參數

+4

請澄清一下:你的問題是什麼,爲什麼你認爲你錯誤地執行了execve()函數?什麼是程序的輸出? –

+2

聲明'parameter'數組在哪裏?它是如何聲明的? '/ bn /'是你的目錄名還是'/ bin /'的拼寫錯誤?如果是後者,你怎麼知道該命令不在'/ usr/bin /'中? 'break'後的'cp = NULL;'應該會產生編譯器警告。 –

+2

爲什麼你將環境設置爲空指針?這有點可疑 - 即使實際上沒有錯。 POSIX要求'_參數envp是一個由空字符結尾的字符指針組成的數組。這些字符串應構成新過程映像的環境。 envp數組由一個空指針終止。''和你的'env'不符合要求。 –

回答

2

有所有類型的問題與您的代碼包括以下內容(其中有些是正確地指出喬納森萊弗勒):

  1. "/bin/"拼錯爲"/bn/"
  2. 由於parameter[0]指向一個字符串字面("/bn/"strcat(parameter[0], cp);您試圖追加到此字符串文字是不正確的。您應該分配一個緩衝區來保存連接的字符串。
  3. 您的令牌化代碼無法正確處理command中的尾隨換行符。
  4. env應該指向以NULL結尾的字符串數組。

一般來說,我認爲在將它們集成到一個更大的程序中之前,我應該把重點放在實現和測試代碼的某些部分。如果您在嘗試將結果傳遞到execve之前測試了read_command,則會發現它不起作用。