2014-01-25 31 views
1

我想實現我自己的shell,有很多東西不能工作,但現在我試圖解決第一個錯誤。 當我的shell正在運行,並且我作爲第一個命令輸入exit時,它可以正常工作,但是,當我輸入exit作爲第二個輸入時,我應該寫入exit以退出shell,如果我輸入它作爲第三個命令,我必須再輸入2次,依此類推。 這是我的代碼。在C中退出(0)只能偶爾工作

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

int main() 
{ 

    int argumentsnum; 
    int status; 

    char *arguments[30]; 
    char *temp; 
    int processes_count=0; 

    printf("My Shell\n"); 
    while (1) 
    { 
     char input[60]; 

     printf("Enter command\n"); 
     while (fgets(input, sizeof(input), stdin) == NULL) 
     { 
      printf("Enter command \n"); 
     } /*end whileloop*/ 

     for (argumentsnum = 0; argumentsnum < 31; argumentsnum++) 
     { 
      temp = strtok(input, " \t\n"); 
      if (temp != NULL) 
      { 
       arguments[argumentsnum] = temp; 
      } /*endif*/ 

     } /*end forloop*/ 
     if (strcmp(arguments[0], "exit") == 0) 
     { 
      printf("Exiting shell\n"); 
      int i; 
      For(i=0;i<processes_count;i++){ 
      exit(0); 
      } 
     } /*endif*/ 
     pid_t id = fork(); 
     processes_count++; 
     if (id == -1) 
     { 
      perror("Grab your own fork :@ \n"); 
      exit(1); 
     } /*endif*/ 
     else if (id == 0) 
     { 
      execvp(arguments[0], arguments); 
     } /*endelse*/ 
     else 
     { 

      wait(&status); 
     } 
    } /*end while(1)*/ 

} /*endmain*/ 
+0

請縮進您的代碼 –

+3

您的'execvp'調用有一個大問題,因爲您沒有正確終止該數組。最後一項必須是「NULL」指針。 –

+0

輸入是字符60,所以你的fgets應該少一個來容納結尾的零 –

回答

2
execvp(arguments[0], arguments); 

你需要的,如果這個調用失敗,做一些事情。如果execvp由於您傳遞了錯誤的命令而失敗,則子進程將繼續向前。這意味着將處理下一個命令,而不是。父母將被卡在wait()的電話中,等待孩子終止。

execvp(arguments[0], arguments); 
perror("execvp"); 
_Exit(1); 
+0

謝謝,它工作。我仍然有其他類型的錯誤,但我會先嚐試自己解決它們。 –